testsuite: skip confirmation in 'gdb_reinitialize_dir'
[binutils-gdb.git] / bfd / peXXigen.c
blobc09d16ed0c0faa6e129778a67dbf5d9afcbd7104
1 /* Support for the generic parts of PE/PEI; the common executable parts.
2 Copyright (C) 1995-2024 Free Software Foundation, Inc.
3 Written by Cygnus Solutions.
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 { ".arch", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
999 { ".bss", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1000 { ".data", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1001 { ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1002 { ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1003 { ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1004 { ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1005 { ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
1006 { ".rsrc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1007 { ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
1008 { ".tls", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1009 { ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1012 pe_required_section_flags * p;
1014 /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
1015 we know exactly what this specific section wants so we remove it
1016 and then allow the must_have field to add it back in if necessary.
1017 However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
1018 default WP_TEXT file flag has been cleared. WP_TEXT may be cleared
1019 by ld --enable-auto-import (if auto-import is actually needed),
1020 by ld --omagic, or by obcopy --writable-text. */
1022 for (p = known_sections;
1023 p < known_sections + ARRAY_SIZE (known_sections);
1024 p++)
1025 if (memcmp (scnhdr_int->s_name, p->section_name, SCNNMLEN) == 0)
1027 if (memcmp (scnhdr_int->s_name, ".text", sizeof ".text")
1028 || (bfd_get_file_flags (abfd) & WP_TEXT))
1029 scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
1030 scnhdr_int->s_flags |= p->must_have;
1031 break;
1034 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1037 if (coff_data (abfd)->link_info
1038 && ! bfd_link_relocatable (coff_data (abfd)->link_info)
1039 && ! bfd_link_pic (coff_data (abfd)->link_info)
1040 && memcmp (scnhdr_int->s_name, ".text", sizeof ".text") == 0)
1042 /* By inference from looking at MS output, the 32 bit field
1043 which is the combination of the number_of_relocs and
1044 number_of_linenos is used for the line number count in
1045 executables. A 16-bit field won't do for cc1. The MS
1046 document says that the number of relocs is zero for
1047 executables, but the 17-th bit has been observed to be there.
1048 Overflow is not an issue: a 4G-line program will overflow a
1049 bunch of other fields long before this! */
1050 H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
1051 H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
1053 else
1055 if (scnhdr_int->s_nlnno <= 0xffff)
1056 H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
1057 else
1059 /* xgettext:c-format */
1060 _bfd_error_handler (_("%pB: line number overflow: 0x%lx > 0xffff"),
1061 abfd, scnhdr_int->s_nlnno);
1062 bfd_set_error (bfd_error_file_truncated);
1063 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
1064 ret = 0;
1067 /* Although we could encode 0xffff relocs here, we do not, to be
1068 consistent with other parts of bfd. Also it lets us warn, as
1069 we should never see 0xffff here w/o having the overflow flag
1070 set. */
1071 if (scnhdr_int->s_nreloc < 0xffff)
1072 H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
1073 else
1075 /* PE can deal with large #s of relocs, but not here. */
1076 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
1077 scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
1078 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1081 return ret;
1084 void
1085 _bfd_XXi_swap_debugdir_in (bfd * abfd, void * ext1, void * in1)
1087 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1;
1088 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1;
1090 in->Characteristics = H_GET_32(abfd, ext->Characteristics);
1091 in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp);
1092 in->MajorVersion = H_GET_16(abfd, ext->MajorVersion);
1093 in->MinorVersion = H_GET_16(abfd, ext->MinorVersion);
1094 in->Type = H_GET_32(abfd, ext->Type);
1095 in->SizeOfData = H_GET_32(abfd, ext->SizeOfData);
1096 in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData);
1097 in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData);
1100 unsigned int
1101 _bfd_XXi_swap_debugdir_out (bfd * abfd, void * inp, void * extp)
1103 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp;
1104 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp;
1106 H_PUT_32(abfd, in->Characteristics, ext->Characteristics);
1107 H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp);
1108 H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion);
1109 H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion);
1110 H_PUT_32(abfd, in->Type, ext->Type);
1111 H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData);
1112 H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData);
1113 H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData);
1115 return sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1118 CODEVIEW_INFO *
1119 _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo,
1120 char **pdb)
1122 char buffer[256+1];
1123 bfd_size_type nread;
1125 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1126 return NULL;
1128 if (length <= sizeof (CV_INFO_PDB70) && length <= sizeof (CV_INFO_PDB20))
1129 return NULL;
1130 if (length > 256)
1131 length = 256;
1132 nread = bfd_read (buffer, length, abfd);
1133 if (length != nread)
1134 return NULL;
1136 /* Ensure null termination of filename. */
1137 memset (buffer + nread, 0, sizeof (buffer) - nread);
1139 cvinfo->CVSignature = H_GET_32 (abfd, buffer);
1140 cvinfo->Age = 0;
1142 if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
1143 && (length > sizeof (CV_INFO_PDB70)))
1145 CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
1147 cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
1149 /* A GUID consists of 4,2,2 byte values in little-endian order, followed
1150 by 8 single bytes. Byte swap them so we can conveniently treat the GUID
1151 as 16 bytes in big-endian order. */
1152 bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
1153 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
1154 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
1155 memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
1157 cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
1158 /* cvinfo->PdbFileName = cvinfo70->PdbFileName; */
1160 if (pdb)
1161 *pdb = xstrdup (cvinfo70->PdbFileName);
1163 return cvinfo;
1165 else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
1166 && (length > sizeof (CV_INFO_PDB20)))
1168 CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
1169 cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
1170 memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
1171 cvinfo->SignatureLength = 4;
1172 /* cvinfo->PdbFileName = cvinfo20->PdbFileName; */
1174 if (pdb)
1175 *pdb = xstrdup (cvinfo20->PdbFileName);
1177 return cvinfo;
1180 return NULL;
1183 unsigned int
1184 _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo,
1185 const char *pdb)
1187 size_t pdb_len = pdb ? strlen (pdb) : 0;
1188 const bfd_size_type size = sizeof (CV_INFO_PDB70) + pdb_len + 1;
1189 bfd_size_type written;
1190 CV_INFO_PDB70 *cvinfo70;
1191 char * buffer;
1193 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1194 return 0;
1196 buffer = bfd_malloc (size);
1197 if (buffer == NULL)
1198 return 0;
1200 cvinfo70 = (CV_INFO_PDB70 *) buffer;
1201 H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
1203 /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
1204 in little-endian order, followed by 8 single bytes. */
1205 bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
1206 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
1207 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
1208 memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
1210 H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
1212 if (pdb == NULL)
1213 cvinfo70->PdbFileName[0] = '\0';
1214 else
1215 memcpy (cvinfo70->PdbFileName, pdb, pdb_len + 1);
1217 written = bfd_write (buffer, size, abfd);
1219 free (buffer);
1221 return written == size ? size : 0;
1224 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
1226 N_("Export Directory [.edata (or where ever we found it)]"),
1227 N_("Import Directory [parts of .idata]"),
1228 N_("Resource Directory [.rsrc]"),
1229 N_("Exception Directory [.pdata]"),
1230 N_("Security Directory"),
1231 N_("Base Relocation Directory [.reloc]"),
1232 N_("Debug Directory"),
1233 N_("Description Directory"),
1234 N_("Special Directory"),
1235 N_("Thread Storage Directory [.tls]"),
1236 N_("Load Configuration Directory"),
1237 N_("Bound Import Directory"),
1238 N_("Import Address Table Directory"),
1239 N_("Delay Import Directory"),
1240 N_("CLR Runtime Header"),
1241 N_("Reserved")
1244 static bool
1245 get_contents_sanity_check (bfd *abfd, asection *section,
1246 bfd_size_type dataoff, bfd_size_type datasize)
1248 if ((section->flags & SEC_HAS_CONTENTS) == 0)
1249 return false;
1250 if (dataoff > section->size
1251 || datasize > section->size - dataoff)
1252 return false;
1253 ufile_ptr filesize = bfd_get_file_size (abfd);
1254 if (filesize != 0
1255 && ((ufile_ptr) section->filepos > filesize
1256 || dataoff > filesize - section->filepos
1257 || datasize > filesize - section->filepos - dataoff))
1258 return false;
1259 return true;
1262 static bool
1263 pe_print_idata (bfd * abfd, void * vfile)
1265 FILE *file = (FILE *) vfile;
1266 bfd_byte *data;
1267 asection *section;
1268 bfd_signed_vma adj;
1269 bfd_size_type datasize = 0;
1270 bfd_size_type dataoff;
1271 bfd_size_type i;
1272 int onaline = 20;
1274 pe_data_type *pe = pe_data (abfd);
1275 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1277 bfd_vma addr;
1279 addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
1281 if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
1283 /* Maybe the extra header isn't there. Look for the section. */
1284 section = bfd_get_section_by_name (abfd, ".idata");
1285 if (section == NULL || (section->flags & SEC_HAS_CONTENTS) == 0)
1286 return true;
1288 addr = section->vma;
1289 datasize = section->size;
1290 if (datasize == 0)
1291 return true;
1293 else
1295 addr += extra->ImageBase;
1296 for (section = abfd->sections; section != NULL; section = section->next)
1298 datasize = section->size;
1299 if (addr >= section->vma && addr < section->vma + datasize)
1300 break;
1303 if (section == NULL)
1305 fprintf (file,
1306 _("\nThere is an import table, but the section containing it could not be found\n"));
1307 return true;
1309 else if (!(section->flags & SEC_HAS_CONTENTS))
1311 fprintf (file,
1312 _("\nThere is an import table in %s, but that section has no contents\n"),
1313 section->name);
1314 return true;
1318 /* xgettext:c-format */
1319 fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
1320 section->name, (unsigned long) addr);
1322 dataoff = addr - section->vma;
1324 fprintf (file,
1325 _("\nThe Import Tables (interpreted %s section contents)\n"),
1326 section->name);
1327 fprintf (file,
1328 _("\
1329 vma: Hint Time Forward DLL First\n\
1330 Table Stamp Chain Name Thunk\n"));
1332 /* Read the whole section. Some of the fields might be before dataoff. */
1333 if (!bfd_malloc_and_get_section (abfd, section, &data))
1335 free (data);
1336 return false;
1339 adj = section->vma - extra->ImageBase;
1341 /* Print all image import descriptors. */
1342 for (i = dataoff; i + onaline <= datasize; i += onaline)
1344 bfd_vma hint_addr;
1345 bfd_vma time_stamp;
1346 bfd_vma forward_chain;
1347 bfd_vma dll_name;
1348 bfd_vma first_thunk;
1349 int idx = 0;
1350 bfd_size_type j;
1351 char *dll;
1353 /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress). */
1354 fprintf (file, " %08lx\t", (unsigned long) (i + adj));
1355 hint_addr = bfd_get_32 (abfd, data + i);
1356 time_stamp = bfd_get_32 (abfd, data + i + 4);
1357 forward_chain = bfd_get_32 (abfd, data + i + 8);
1358 dll_name = bfd_get_32 (abfd, data + i + 12);
1359 first_thunk = bfd_get_32 (abfd, data + i + 16);
1361 fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
1362 (unsigned long) hint_addr,
1363 (unsigned long) time_stamp,
1364 (unsigned long) forward_chain,
1365 (unsigned long) dll_name,
1366 (unsigned long) first_thunk);
1368 if (hint_addr == 0 && first_thunk == 0)
1369 break;
1371 if (dll_name - adj >= section->size)
1372 break;
1374 dll = (char *) data + dll_name - adj;
1375 /* PR 17512 file: 078-12277-0.004. */
1376 bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
1377 fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
1379 /* PR 21546: When the Hint Address is zero,
1380 we try the First Thunk instead. */
1381 if (hint_addr == 0)
1382 hint_addr = first_thunk;
1384 if (hint_addr != 0 && hint_addr - adj < datasize)
1386 bfd_byte *ft_data;
1387 asection *ft_section;
1388 bfd_vma ft_addr;
1389 bfd_size_type ft_datasize;
1390 int ft_idx;
1391 int ft_allocated;
1393 fprintf (file, _("\tvma: Ordinal Hint Member-Name Bound-To\n"));
1395 idx = hint_addr - adj;
1397 ft_addr = first_thunk + extra->ImageBase;
1398 ft_idx = first_thunk - adj;
1399 ft_data = data + ft_idx;
1400 ft_datasize = datasize - ft_idx;
1401 ft_allocated = 0;
1403 if (first_thunk != hint_addr)
1405 /* Find the section which contains the first thunk. */
1406 for (ft_section = abfd->sections;
1407 ft_section != NULL;
1408 ft_section = ft_section->next)
1410 if (ft_addr >= ft_section->vma
1411 && ft_addr < ft_section->vma + ft_section->size)
1412 break;
1415 if (ft_section == NULL)
1417 fprintf (file,
1418 _("\nThere is a first thunk, but the section containing it could not be found\n"));
1419 continue;
1422 /* Now check to see if this section is the same as our current
1423 section. If it is not then we will have to load its data in. */
1424 if (ft_section != section)
1426 ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
1427 ft_datasize = ft_section->size - ft_idx;
1428 if (!get_contents_sanity_check (abfd, ft_section,
1429 ft_idx, ft_datasize))
1430 continue;
1431 ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
1432 if (ft_data == NULL)
1433 continue;
1435 /* Read ft_datasize bytes starting at offset ft_idx. */
1436 if (!bfd_get_section_contents (abfd, ft_section, ft_data,
1437 (bfd_vma) ft_idx, ft_datasize))
1439 free (ft_data);
1440 continue;
1442 ft_allocated = 1;
1446 /* Print HintName vector entries. */
1447 #ifdef COFF_WITH_pex64
1448 for (j = 0; idx + j + 8 <= datasize; j += 8)
1450 bfd_size_type amt;
1451 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1452 unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
1454 if (!member && !member_high)
1455 break;
1457 amt = member - adj;
1459 if (HighBitSet (member_high))
1461 /* in low 16 bits is ordinal number, other bits are reserved */
1462 unsigned int ordinal = member & 0xffff;
1463 fprintf (file, "\t%08lx %5u <none> <none>",
1464 (unsigned long)(first_thunk + j), ordinal);
1466 /* PR binutils/17512: Handle corrupt PE data. */
1467 else if (amt >= datasize || amt + 2 >= datasize)
1468 fprintf (file, _("\t<corrupt: 0x%08lx>"), member);
1469 else
1471 unsigned int hint;
1472 char *member_name;
1474 /* First 16 bits is hint name index, rest is the name */
1475 hint = bfd_get_16 (abfd, data + amt);
1476 member_name = (char *) data + amt + 2;
1477 fprintf (file, "\t%08lx <none> %04x %.*s",
1478 (unsigned long)(first_thunk + j), hint,
1479 (int) (datasize - (amt + 2)), member_name);
1482 /* If the time stamp is not zero, the import address
1483 table holds actual addresses. */
1484 if (time_stamp != 0
1485 && first_thunk != 0
1486 && first_thunk != hint_addr
1487 && j + 4 <= ft_datasize)
1488 fprintf (file, "\t%08lx",
1489 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1491 fprintf (file, "\n");
1493 #else
1494 for (j = 0; idx + j + 4 <= datasize; j += 4)
1496 bfd_size_type amt;
1497 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1499 /* Print single IMAGE_IMPORT_BY_NAME vector. */
1500 if (member == 0)
1501 break;
1503 amt = member - adj;
1505 if (HighBitSet (member))
1507 /* in low 16 bits is ordinal number, other bits are reserved */
1508 unsigned int ordinal = member & 0xffff;
1509 fprintf (file, "\t%08lx %5u <none> <none>", (unsigned long)(first_thunk + j), ordinal);
1511 /* PR binutils/17512: Handle corrupt PE data. */
1512 else if (amt >= datasize || amt + 2 >= datasize)
1513 fprintf (file, _("\t<corrupt: 0x%08lx>"), member);
1514 else
1516 unsigned int hint;
1517 char *member_name;
1519 /* First 16 bits is hint name index, rest is the name */
1520 hint = bfd_get_16 (abfd, data + amt);
1521 member_name = (char *) data + amt + 2;
1522 fprintf (file, "\t%08lx <none> %04x %.*s",
1523 (unsigned long)(first_thunk + j), hint,
1524 (int) (datasize - (amt + 2)), member_name);
1527 /* If the time stamp is not zero, the import address
1528 table holds actual addresses. */
1529 if (time_stamp != 0
1530 && first_thunk != 0
1531 && first_thunk != hint_addr
1532 && j + 4 <= ft_datasize)
1533 fprintf (file, "\t%08lx",
1534 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1536 fprintf (file, "\n");
1538 #endif
1539 if (ft_allocated)
1540 free (ft_data);
1543 fprintf (file, "\n");
1546 free (data);
1548 return true;
1551 static bool
1552 pe_print_edata (bfd * abfd, void * vfile)
1554 FILE *file = (FILE *) vfile;
1555 bfd_byte *data;
1556 asection *section;
1557 bfd_size_type datasize = 0;
1558 bfd_size_type dataoff;
1559 bfd_size_type i;
1560 bfd_vma adj;
1561 struct EDT_type
1563 long export_flags; /* Reserved - should be zero. */
1564 long time_stamp;
1565 short major_ver;
1566 short minor_ver;
1567 bfd_vma name; /* RVA - relative to image base. */
1568 long base; /* Ordinal base. */
1569 unsigned long num_functions;/* Number in the export address table. */
1570 unsigned long num_names; /* Number in the name pointer table. */
1571 bfd_vma eat_addr; /* RVA to the export address table. */
1572 bfd_vma npt_addr; /* RVA to the Export Name Pointer Table. */
1573 bfd_vma ot_addr; /* RVA to the Ordinal Table. */
1574 } edt;
1576 pe_data_type *pe = pe_data (abfd);
1577 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1579 bfd_vma addr;
1581 addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
1583 if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
1585 /* Maybe the extra header isn't there. Look for the section. */
1586 section = bfd_get_section_by_name (abfd, ".edata");
1587 if (section == NULL)
1588 return true;
1590 addr = section->vma;
1591 dataoff = 0;
1592 datasize = section->size;
1593 if (datasize == 0)
1594 return true;
1596 else
1598 addr += extra->ImageBase;
1600 for (section = abfd->sections; section != NULL; section = section->next)
1601 if (addr >= section->vma && addr < section->vma + section->size)
1602 break;
1604 if (section == NULL)
1606 fprintf (file,
1607 _("\nThere is an export table, but the section containing it could not be found\n"));
1608 return true;
1611 dataoff = addr - section->vma;
1612 datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
1615 /* PR 17512: Handle corrupt PE binaries. */
1616 if (datasize < 40)
1618 fprintf (file,
1619 /* xgettext:c-format */
1620 _("\nThere is an export table in %s, but it is too small (%d)\n"),
1621 section->name, (int) datasize);
1622 return true;
1625 if (!get_contents_sanity_check (abfd, section, dataoff, datasize))
1627 fprintf (file,
1628 _("\nThere is an export table in %s, but contents cannot be read\n"),
1629 section->name);
1630 return true;
1633 /* xgettext:c-format */
1634 fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
1635 section->name, (unsigned long) addr);
1637 data = (bfd_byte *) bfd_malloc (datasize);
1638 if (data == NULL)
1639 return false;
1641 if (! bfd_get_section_contents (abfd, section, data,
1642 (file_ptr) dataoff, datasize))
1644 free (data);
1645 return false;
1648 /* Go get Export Directory Table. */
1649 edt.export_flags = bfd_get_32 (abfd, data + 0);
1650 edt.time_stamp = bfd_get_32 (abfd, data + 4);
1651 edt.major_ver = bfd_get_16 (abfd, data + 8);
1652 edt.minor_ver = bfd_get_16 (abfd, data + 10);
1653 edt.name = bfd_get_32 (abfd, data + 12);
1654 edt.base = bfd_get_32 (abfd, data + 16);
1655 edt.num_functions = bfd_get_32 (abfd, data + 20);
1656 edt.num_names = bfd_get_32 (abfd, data + 24);
1657 edt.eat_addr = bfd_get_32 (abfd, data + 28);
1658 edt.npt_addr = bfd_get_32 (abfd, data + 32);
1659 edt.ot_addr = bfd_get_32 (abfd, data + 36);
1661 adj = section->vma - extra->ImageBase + dataoff;
1663 /* Dump the EDT first. */
1664 fprintf (file,
1665 _("\nThe Export Tables (interpreted %s section contents)\n\n"),
1666 section->name);
1668 fprintf (file,
1669 _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
1671 fprintf (file,
1672 _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
1674 fprintf (file,
1675 /* xgettext:c-format */
1676 _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
1678 fprintf (file,
1679 _("Name \t\t\t\t"));
1680 bfd_fprintf_vma (abfd, file, edt.name);
1682 if ((edt.name >= adj) && (edt.name < adj + datasize))
1683 fprintf (file, " %.*s\n",
1684 (int) (datasize - (edt.name - adj)),
1685 data + edt.name - adj);
1686 else
1687 fprintf (file, "(outside .edata section)\n");
1689 fprintf (file,
1690 _("Ordinal Base \t\t\t%ld\n"), edt.base);
1692 fprintf (file,
1693 _("Number in:\n"));
1695 fprintf (file,
1696 _("\tExport Address Table \t\t%08lx\n"),
1697 edt.num_functions);
1699 fprintf (file,
1700 _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
1702 fprintf (file,
1703 _("Table Addresses\n"));
1705 fprintf (file,
1706 _("\tExport Address Table \t\t"));
1707 bfd_fprintf_vma (abfd, file, edt.eat_addr);
1708 fprintf (file, "\n");
1710 fprintf (file,
1711 _("\tName Pointer Table \t\t"));
1712 bfd_fprintf_vma (abfd, file, edt.npt_addr);
1713 fprintf (file, "\n");
1715 fprintf (file,
1716 _("\tOrdinal Table \t\t\t"));
1717 bfd_fprintf_vma (abfd, file, edt.ot_addr);
1718 fprintf (file, "\n");
1720 /* The next table to find is the Export Address Table. It's basically
1721 a list of pointers that either locate a function in this dll, or
1722 forward the call to another dll. Something like:
1723 typedef union
1725 long export_rva;
1726 long forwarder_rva;
1727 } export_address_table_entry; */
1729 fprintf (file,
1730 _("\nExport Address Table -- Ordinal Base %ld\n"),
1731 edt.base);
1732 fprintf (file, "\t Ordinal Address Type\n");
1734 /* PR 17512: Handle corrupt PE binaries. */
1735 /* PR 17512 file: 140-165018-0.004. */
1736 if (edt.eat_addr - adj >= datasize
1737 /* PR 17512: file: 092b1829 */
1738 || (edt.num_functions + 1) * 4 < edt.num_functions
1739 || edt.eat_addr - adj + (edt.num_functions + 1) * 4 > datasize)
1740 fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
1741 (long) edt.eat_addr,
1742 (long) edt.num_functions);
1743 else for (i = 0; i < edt.num_functions; ++i)
1745 bfd_vma eat_member = bfd_get_32 (abfd,
1746 data + edt.eat_addr + (i * 4) - adj);
1747 if (eat_member == 0)
1748 continue;
1750 if (eat_member - adj <= datasize)
1752 /* This rva is to a name (forwarding function) in our section. */
1753 /* Should locate a function descriptor. */
1754 fprintf (file,
1755 "\t[%4ld] +base[%4ld] %08lx %s -- %.*s\n",
1756 (long) i,
1757 (long) (i + edt.base),
1758 (unsigned long) eat_member,
1759 _("Forwarder RVA"),
1760 (int)(datasize - (eat_member - adj)),
1761 data + eat_member - adj);
1763 else
1765 /* Should locate a function descriptor in the reldata section. */
1766 fprintf (file,
1767 "\t[%4ld] +base[%4ld] %08lx %s\n",
1768 (long) i,
1769 (long) (i + edt.base),
1770 (unsigned long) eat_member,
1771 _("Export RVA"));
1775 /* The Export Name Pointer Table is paired with the Export Ordinal Table. */
1776 /* Dump them in parallel for clarity. */
1777 fprintf (file,
1778 _("\n[Ordinal/Name Pointer] Table -- Ordinal Base %ld\n"),
1779 edt.base);
1780 fprintf (file, "\t Ordinal Hint Name\n");
1782 /* PR 17512: Handle corrupt PE binaries. */
1783 if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
1784 /* PR 17512: file: bb68816e. */
1785 || edt.num_names * 4 < edt.num_names
1786 || (data + edt.npt_addr - adj) < data)
1787 /* xgettext:c-format */
1788 fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
1789 (long) edt.npt_addr,
1790 (long) edt.num_names);
1791 /* PR 17512: file: 140-147171-0.004. */
1792 else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
1793 || data + edt.ot_addr - adj < data)
1794 /* xgettext:c-format */
1795 fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
1796 (long) edt.ot_addr,
1797 (long) edt.num_names);
1798 else for (i = 0; i < edt.num_names; ++i)
1800 bfd_vma name_ptr;
1801 bfd_vma ord;
1803 ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
1804 name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
1806 if ((name_ptr - adj) >= datasize)
1808 /* xgettext:c-format */
1809 fprintf (file, _("\t[%4ld] +base[%4ld] %04lx <corrupt offset: %lx>\n"),
1810 (long) ord, (long) (ord + edt.base), (long) i, (long) name_ptr);
1812 else
1814 char * name = (char *) data + name_ptr - adj;
1816 fprintf (file,
1817 "\t[%4ld] +base[%4ld] %04lx %.*s\n",
1818 (long) ord, (long) (ord + edt.base), (long) i,
1819 (int)((char *)(data + datasize) - name), name);
1823 free (data);
1825 return true;
1828 /* This really is architecture dependent. On IA-64, a .pdata entry
1829 consists of three dwords containing relative virtual addresses that
1830 specify the start and end address of the code range the entry
1831 covers and the address of the corresponding unwind info data.
1833 On ARM and SH-4, a compressed PDATA structure is used :
1834 _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
1835 _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
1836 See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
1838 This is the version for uncompressed data. */
1840 static bool
1841 pe_print_pdata (bfd * abfd, void * vfile)
1843 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
1844 # define PDATA_ROW_SIZE (3 * 8)
1845 #else
1846 # define PDATA_ROW_SIZE (5 * 4)
1847 #endif
1848 FILE *file = (FILE *) vfile;
1849 bfd_byte *data = 0;
1850 asection *section = bfd_get_section_by_name (abfd, ".pdata");
1851 bfd_size_type datasize = 0;
1852 bfd_size_type i;
1853 bfd_size_type start, stop;
1854 int onaline = PDATA_ROW_SIZE;
1856 if (section == NULL
1857 || (section->flags & SEC_HAS_CONTENTS) == 0
1858 || coff_section_data (abfd, section) == NULL
1859 || pei_section_data (abfd, section) == NULL)
1860 return true;
1862 stop = pei_section_data (abfd, section)->virt_size;
1863 if ((stop % onaline) != 0)
1864 fprintf (file,
1865 /* xgettext:c-format */
1866 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
1867 (long) stop, onaline);
1869 fprintf (file,
1870 _("\nThe Function Table (interpreted .pdata section contents)\n"));
1871 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
1872 fprintf (file,
1873 _(" vma:\t\t\tBegin Address End Address Unwind Info\n"));
1874 #else
1875 fprintf (file, _("\
1876 vma:\t\tBegin End EH EH PrologEnd Exception\n\
1877 \t\tAddress Address Handler Data Address Mask\n"));
1878 #endif
1880 datasize = section->size;
1881 if (datasize == 0)
1882 return true;
1884 /* PR 17512: file: 002-193900-0.004. */
1885 if (datasize < stop)
1887 /* xgettext:c-format */
1888 fprintf (file, _("Virtual size of .pdata section (%ld) larger than real size (%ld)\n"),
1889 (long) stop, (long) datasize);
1890 return false;
1893 if (! bfd_malloc_and_get_section (abfd, section, &data))
1895 free (data);
1896 return false;
1899 start = 0;
1901 for (i = start; i < stop; i += onaline)
1903 bfd_vma begin_addr;
1904 bfd_vma end_addr;
1905 bfd_vma eh_handler;
1906 bfd_vma eh_data;
1907 bfd_vma prolog_end_addr;
1908 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1909 int em_data;
1910 #endif
1912 if (i + PDATA_ROW_SIZE > stop)
1913 break;
1915 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
1916 end_addr = GET_PDATA_ENTRY (abfd, data + i + 4);
1917 eh_handler = GET_PDATA_ENTRY (abfd, data + i + 8);
1918 eh_data = GET_PDATA_ENTRY (abfd, data + i + 12);
1919 prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
1921 if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
1922 && eh_data == 0 && prolog_end_addr == 0)
1923 /* We are probably into the padding of the section now. */
1924 break;
1926 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1927 em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
1928 #endif
1929 eh_handler &= ~(bfd_vma) 0x3;
1930 prolog_end_addr &= ~(bfd_vma) 0x3;
1932 fputc (' ', file);
1933 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
1934 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
1935 bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
1936 bfd_fprintf_vma (abfd, file, eh_handler);
1937 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1938 fputc (' ', file);
1939 bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
1940 bfd_fprintf_vma (abfd, file, prolog_end_addr);
1941 fprintf (file, " %x", em_data);
1942 #endif
1943 fprintf (file, "\n");
1946 free (data);
1948 return true;
1949 #undef PDATA_ROW_SIZE
1952 typedef struct sym_cache
1954 int symcount;
1955 asymbol ** syms;
1956 } sym_cache;
1958 static asymbol **
1959 slurp_symtab (bfd *abfd, sym_cache *psc)
1961 asymbol ** sy = NULL;
1962 long storage;
1964 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
1966 psc->symcount = 0;
1967 return NULL;
1970 storage = bfd_get_symtab_upper_bound (abfd);
1971 if (storage < 0)
1972 return NULL;
1973 if (storage)
1975 sy = (asymbol **) bfd_malloc (storage);
1976 if (sy == NULL)
1977 return NULL;
1980 psc->symcount = bfd_canonicalize_symtab (abfd, sy);
1981 if (psc->symcount < 0)
1982 return NULL;
1983 return sy;
1986 static const char *
1987 my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
1989 int i;
1991 if (psc->syms == 0)
1992 psc->syms = slurp_symtab (abfd, psc);
1994 for (i = 0; i < psc->symcount; i++)
1996 if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
1997 return psc->syms[i]->name;
2000 return NULL;
2003 static void
2004 cleanup_syms (sym_cache *psc)
2006 psc->symcount = 0;
2007 free (psc->syms);
2008 psc->syms = NULL;
2011 /* This is the version for "compressed" pdata. */
2013 bool
2014 _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
2016 # define PDATA_ROW_SIZE (2 * 4)
2017 FILE *file = (FILE *) vfile;
2018 bfd_byte *data = NULL;
2019 asection *section = bfd_get_section_by_name (abfd, ".pdata");
2020 bfd_size_type datasize = 0;
2021 bfd_size_type i;
2022 bfd_size_type start, stop;
2023 int onaline = PDATA_ROW_SIZE;
2024 struct sym_cache cache = {0, 0} ;
2026 if (section == NULL
2027 || (section->flags & SEC_HAS_CONTENTS) == 0
2028 || coff_section_data (abfd, section) == NULL
2029 || pei_section_data (abfd, section) == NULL)
2030 return true;
2032 stop = pei_section_data (abfd, section)->virt_size;
2033 if ((stop % onaline) != 0)
2034 fprintf (file,
2035 /* xgettext:c-format */
2036 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
2037 (long) stop, onaline);
2039 fprintf (file,
2040 _("\nThe Function Table (interpreted .pdata section contents)\n"));
2042 fprintf (file, _("\
2043 vma:\t\tBegin Prolog Function Flags Exception EH\n\
2044 \t\tAddress Length Length 32b exc Handler Data\n"));
2046 datasize = section->size;
2047 if (datasize == 0)
2048 return true;
2050 if (! bfd_malloc_and_get_section (abfd, section, &data))
2052 free (data);
2053 return false;
2056 start = 0;
2057 if (stop > datasize)
2058 stop = datasize;
2060 for (i = start; i < stop; i += onaline)
2062 bfd_vma begin_addr;
2063 bfd_vma other_data;
2064 bfd_vma prolog_length, function_length;
2065 int flag32bit, exception_flag;
2066 asection *tsection;
2068 if (i + PDATA_ROW_SIZE > stop)
2069 break;
2071 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
2072 other_data = GET_PDATA_ENTRY (abfd, data + i + 4);
2074 if (begin_addr == 0 && other_data == 0)
2075 /* We are probably into the padding of the section now. */
2076 break;
2078 prolog_length = (other_data & 0x000000FF);
2079 function_length = (other_data & 0x3FFFFF00) >> 8;
2080 flag32bit = (int)((other_data & 0x40000000) >> 30);
2081 exception_flag = (int)((other_data & 0x80000000) >> 31);
2083 fputc (' ', file);
2084 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
2085 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
2086 bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
2087 bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
2088 fprintf (file, "%2d %2d ", flag32bit, exception_flag);
2090 /* Get the exception handler's address and the data passed from the
2091 .text section. This is really the data that belongs with the .pdata
2092 but got "compressed" out for the ARM and SH4 architectures. */
2093 tsection = bfd_get_section_by_name (abfd, ".text");
2094 if (tsection && coff_section_data (abfd, tsection)
2095 && pei_section_data (abfd, tsection))
2097 bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
2098 bfd_byte *tdata;
2100 tdata = (bfd_byte *) bfd_malloc (8);
2101 if (tdata)
2103 if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
2105 bfd_vma eh, eh_data;
2107 eh = bfd_get_32 (abfd, tdata);
2108 eh_data = bfd_get_32 (abfd, tdata + 4);
2109 fprintf (file, "%08x ", (unsigned int) eh);
2110 fprintf (file, "%08x", (unsigned int) eh_data);
2111 if (eh != 0)
2113 const char *s = my_symbol_for_address (abfd, eh, &cache);
2115 if (s)
2116 fprintf (file, " (%s) ", s);
2119 free (tdata);
2123 fprintf (file, "\n");
2126 free (data);
2128 cleanup_syms (& cache);
2130 return true;
2131 #undef PDATA_ROW_SIZE
2135 #define IMAGE_REL_BASED_HIGHADJ 4
2136 static const char * const tbl[] =
2138 "ABSOLUTE",
2139 "HIGH",
2140 "LOW",
2141 "HIGHLOW",
2142 "HIGHADJ",
2143 "MIPS_JMPADDR",
2144 "SECTION",
2145 "REL32",
2146 "RESERVED1",
2147 "MIPS_JMPADDR16",
2148 "DIR64",
2149 "HIGH3ADJ",
2150 "UNKNOWN", /* MUST be last. */
2153 static bool
2154 pe_print_reloc (bfd * abfd, void * vfile)
2156 FILE *file = (FILE *) vfile;
2157 bfd_byte *data = 0;
2158 asection *section = bfd_get_section_by_name (abfd, ".reloc");
2159 bfd_byte *p, *end;
2161 if (section == NULL
2162 || section->size == 0
2163 || (section->flags & SEC_HAS_CONTENTS) == 0)
2164 return true;
2166 fprintf (file,
2167 _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
2169 if (! bfd_malloc_and_get_section (abfd, section, &data))
2171 free (data);
2172 return false;
2175 p = data;
2176 end = data + section->size;
2177 while (p + 8 <= end)
2179 int j;
2180 bfd_vma virtual_address;
2181 unsigned long number, size;
2182 bfd_byte *chunk_end;
2184 /* The .reloc section is a sequence of blocks, with a header consisting
2185 of two 32 bit quantities, followed by a number of 16 bit entries. */
2186 virtual_address = bfd_get_32 (abfd, p);
2187 size = bfd_get_32 (abfd, p + 4);
2188 p += 8;
2189 number = (size - 8) / 2;
2191 if (size == 0)
2192 break;
2194 fprintf (file,
2195 /* xgettext:c-format */
2196 _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
2197 (unsigned long) virtual_address, size, size, number);
2199 chunk_end = p - 8 + size;
2200 if (chunk_end > end)
2201 chunk_end = end;
2202 j = 0;
2203 while (p + 2 <= chunk_end)
2205 unsigned short e = bfd_get_16 (abfd, p);
2206 unsigned int t = (e & 0xF000) >> 12;
2207 int off = e & 0x0FFF;
2209 if (t >= sizeof (tbl) / sizeof (tbl[0]))
2210 t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
2212 fprintf (file,
2213 /* xgettext:c-format */
2214 _("\treloc %4d offset %4x [%4lx] %s"),
2215 j, off, (unsigned long) (off + virtual_address), tbl[t]);
2217 p += 2;
2218 j++;
2220 /* HIGHADJ takes an argument, - the next record *is* the
2221 low 16 bits of addend. */
2222 if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
2224 fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
2225 p += 2;
2226 j++;
2229 fprintf (file, "\n");
2233 free (data);
2235 return true;
2238 /* A data structure describing the regions of a .rsrc section.
2239 Some fields are filled in as the section is parsed. */
2241 typedef struct rsrc_regions
2243 bfd_byte * section_start;
2244 bfd_byte * section_end;
2245 bfd_byte * strings_start;
2246 bfd_byte * resource_start;
2247 } rsrc_regions;
2249 static bfd_byte *
2250 rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
2251 rsrc_regions *, bfd_vma);
2253 /* Print the resource entry at DATA, with the text indented by INDENT.
2254 Recusively calls rsrc_print_resource_directory to print the contents
2255 of directory entries.
2256 Returns the address of the end of the data associated with the entry
2257 or section_end + 1 upon failure. */
2259 static bfd_byte *
2260 rsrc_print_resource_entries (FILE *file,
2261 bfd *abfd,
2262 unsigned int indent,
2263 bool is_name,
2264 bfd_byte *data,
2265 rsrc_regions *regions,
2266 bfd_vma rva_bias)
2268 unsigned long entry, addr, size;
2269 bfd_byte * leaf;
2271 if (data + 8 >= regions->section_end)
2272 return regions->section_end + 1;
2274 /* xgettext:c-format */
2275 fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
2277 entry = (unsigned long) bfd_get_32 (abfd, data);
2278 if (is_name)
2280 bfd_byte * name;
2282 /* Note - the documentation says that this field is an RVA value
2283 but windres appears to produce a section relative offset with
2284 the top bit set. Support both styles for now. */
2285 if (HighBitSet (entry))
2286 name = regions->section_start + WithoutHighBit (entry);
2287 else
2288 name = regions->section_start + entry - rva_bias;
2290 if (name + 2 < regions->section_end && name > regions->section_start)
2292 unsigned int len;
2294 if (regions->strings_start == NULL)
2295 regions->strings_start = name;
2297 len = bfd_get_16 (abfd, name);
2299 fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
2301 if (name + 2 + len * 2 < regions->section_end)
2303 /* This strange loop is to cope with multibyte characters. */
2304 while (len --)
2306 char c;
2308 name += 2;
2309 c = * name;
2310 /* Avoid printing control characters. */
2311 if (c > 0 && c < 32)
2312 fprintf (file, "^%c", c + 64);
2313 else
2314 fprintf (file, "%.1s", name);
2317 else
2319 fprintf (file, _("<corrupt string length: %#x>\n"), len);
2320 /* PR binutils/17512: Do not try to continue decoding a
2321 corrupted resource section. It is likely to end up with
2322 reams of extraneous output. FIXME: We could probably
2323 continue if we disable the printing of strings... */
2324 return regions->section_end + 1;
2327 else
2329 fprintf (file, _("<corrupt string offset: %#lx>\n"), entry);
2330 return regions->section_end + 1;
2333 else
2334 fprintf (file, _("ID: %#08lx"), entry);
2336 entry = (long) bfd_get_32 (abfd, data + 4);
2337 fprintf (file, _(", Value: %#08lx\n"), entry);
2339 if (HighBitSet (entry))
2341 data = regions->section_start + WithoutHighBit (entry);
2342 if (data <= regions->section_start || data > regions->section_end)
2343 return regions->section_end + 1;
2345 /* FIXME: PR binutils/17512: A corrupt file could contain a loop
2346 in the resource table. We need some way to detect this. */
2347 return rsrc_print_resource_directory (file, abfd, indent + 1, data,
2348 regions, rva_bias);
2351 leaf = regions->section_start + entry;
2353 if (leaf + 16 >= regions->section_end
2354 /* PR 17512: file: 055dff7e. */
2355 || leaf < regions->section_start)
2356 return regions->section_end + 1;
2358 /* xgettext:c-format */
2359 fprintf (file, _("%03x %*.s Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
2360 (int) (entry), indent, " ",
2361 addr = (long) bfd_get_32 (abfd, leaf),
2362 size = (long) bfd_get_32 (abfd, leaf + 4),
2363 (int) bfd_get_32 (abfd, leaf + 8));
2365 /* Check that the reserved entry is 0. */
2366 if (bfd_get_32 (abfd, leaf + 12) != 0
2367 /* And that the data address/size is valid too. */
2368 || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
2369 return regions->section_end + 1;
2371 if (regions->resource_start == NULL)
2372 regions->resource_start = regions->section_start + (addr - rva_bias);
2374 return regions->section_start + (addr - rva_bias) + size;
2377 #define max(a,b) ((a) > (b) ? (a) : (b))
2378 #define min(a,b) ((a) < (b) ? (a) : (b))
2380 static bfd_byte *
2381 rsrc_print_resource_directory (FILE * file,
2382 bfd * abfd,
2383 unsigned int indent,
2384 bfd_byte * data,
2385 rsrc_regions * regions,
2386 bfd_vma rva_bias)
2388 unsigned int num_names, num_ids;
2389 bfd_byte * highest_data = data;
2391 if (data + 16 >= regions->section_end)
2392 return regions->section_end + 1;
2394 fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
2395 switch (indent)
2397 case 0: fprintf (file, "Type"); break;
2398 case 2: fprintf (file, "Name"); break;
2399 case 4: fprintf (file, "Language"); break;
2400 default:
2401 fprintf (file, _("<unknown directory type: %d>\n"), indent);
2402 /* FIXME: For now we end the printing here. If in the
2403 future more directory types are added to the RSRC spec
2404 then we will need to change this. */
2405 return regions->section_end + 1;
2408 /* xgettext:c-format */
2409 fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
2410 (int) bfd_get_32 (abfd, data),
2411 (long) bfd_get_32 (abfd, data + 4),
2412 (int) bfd_get_16 (abfd, data + 8),
2413 (int) bfd_get_16 (abfd, data + 10),
2414 num_names = (int) bfd_get_16 (abfd, data + 12),
2415 num_ids = (int) bfd_get_16 (abfd, data + 14));
2416 data += 16;
2418 while (num_names --)
2420 bfd_byte * entry_end;
2422 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, true,
2423 data, regions, rva_bias);
2424 data += 8;
2425 highest_data = max (highest_data, entry_end);
2426 if (entry_end >= regions->section_end)
2427 return entry_end;
2430 while (num_ids --)
2432 bfd_byte * entry_end;
2434 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, false,
2435 data, regions, rva_bias);
2436 data += 8;
2437 highest_data = max (highest_data, entry_end);
2438 if (entry_end >= regions->section_end)
2439 return entry_end;
2442 return max (highest_data, data);
2445 /* Display the contents of a .rsrc section. We do not try to
2446 reproduce the resources, windres does that. Instead we dump
2447 the tables in a human readable format. */
2449 static bool
2450 rsrc_print_section (bfd * abfd, void * vfile)
2452 bfd_vma rva_bias;
2453 pe_data_type * pe;
2454 FILE * file = (FILE *) vfile;
2455 bfd_size_type datasize;
2456 asection * section;
2457 bfd_byte * data;
2458 rsrc_regions regions;
2460 pe = pe_data (abfd);
2461 if (pe == NULL)
2462 return true;
2464 section = bfd_get_section_by_name (abfd, ".rsrc");
2465 if (section == NULL)
2466 return true;
2467 if (!(section->flags & SEC_HAS_CONTENTS))
2468 return true;
2470 datasize = section->size;
2471 if (datasize == 0)
2472 return true;
2474 rva_bias = section->vma - pe->pe_opthdr.ImageBase;
2476 if (! bfd_malloc_and_get_section (abfd, section, & data))
2478 free (data);
2479 return false;
2482 regions.section_start = data;
2483 regions.section_end = data + datasize;
2484 regions.strings_start = NULL;
2485 regions.resource_start = NULL;
2487 fflush (file);
2488 fprintf (file, "\nThe .rsrc Resource Directory section:\n");
2490 while (data < regions.section_end)
2492 bfd_byte * p = data;
2494 data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
2496 if (data == regions.section_end + 1)
2497 fprintf (file, _("Corrupt .rsrc section detected!\n"));
2498 else
2500 /* Align data before continuing. */
2501 int align = (1 << section->alignment_power) - 1;
2503 data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
2504 rva_bias += data - p;
2506 /* For reasons that are unclear .rsrc sections are sometimes created
2507 aligned to a 1^3 boundary even when their alignment is set at
2508 1^2. Catch that case here before we issue a spurious warning
2509 message. */
2510 if (data == (regions.section_end - 4))
2511 data = regions.section_end;
2512 else if (data < regions.section_end)
2514 /* If the extra data is all zeros then do not complain.
2515 This is just padding so that the section meets the
2516 page size requirements. */
2517 while (++ data < regions.section_end)
2518 if (*data != 0)
2519 break;
2520 if (data < regions.section_end)
2521 fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
2526 if (regions.strings_start != NULL)
2527 fprintf (file, _(" String table starts at offset: %#03x\n"),
2528 (int) (regions.strings_start - regions.section_start));
2529 if (regions.resource_start != NULL)
2530 fprintf (file, _(" Resources start at offset: %#03x\n"),
2531 (int) (regions.resource_start - regions.section_start));
2533 free (regions.section_start);
2534 return true;
2537 #define IMAGE_NUMBEROF_DEBUG_TYPES 17
2539 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
2541 "Unknown",
2542 "COFF",
2543 "CodeView",
2544 "FPO",
2545 "Misc",
2546 "Exception",
2547 "Fixup",
2548 "OMAP-to-SRC",
2549 "OMAP-from-SRC",
2550 "Borland",
2551 "Reserved",
2552 "CLSID",
2553 "Feature",
2554 "CoffGrp",
2555 "ILTCG",
2556 "MPX",
2557 "Repro",
2560 static bool
2561 pe_print_debugdata (bfd * abfd, void * vfile)
2563 FILE *file = (FILE *) vfile;
2564 pe_data_type *pe = pe_data (abfd);
2565 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2566 asection *section;
2567 bfd_byte *data = 0;
2568 bfd_size_type dataoff;
2569 unsigned int i, j;
2571 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2572 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2574 if (size == 0)
2575 return true;
2577 addr += extra->ImageBase;
2578 for (section = abfd->sections; section != NULL; section = section->next)
2580 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2581 break;
2584 if (section == NULL)
2586 fprintf (file,
2587 _("\nThere is a debug directory, but the section containing it could not be found\n"));
2588 return true;
2590 else if (!(section->flags & SEC_HAS_CONTENTS))
2592 fprintf (file,
2593 _("\nThere is a debug directory in %s, but that section has no contents\n"),
2594 section->name);
2595 return true;
2597 else if (section->size < size)
2599 fprintf (file,
2600 _("\nError: section %s contains the debug data starting address but it is too small\n"),
2601 section->name);
2602 return false;
2605 fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
2606 section->name, (unsigned long) addr);
2608 dataoff = addr - section->vma;
2610 if (size > (section->size - dataoff))
2612 fprintf (file, _("The debug data size field in the data directory is too big for the section"));
2613 return false;
2616 fprintf (file,
2617 _("Type Size Rva Offset\n"));
2619 /* Read the whole section. */
2620 if (!bfd_malloc_and_get_section (abfd, section, &data))
2622 free (data);
2623 return false;
2626 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2628 const char *type_name;
2629 struct external_IMAGE_DEBUG_DIRECTORY *ext
2630 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2631 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2633 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2635 if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
2636 type_name = debug_type_names[0];
2637 else
2638 type_name = debug_type_names[idd.Type];
2640 fprintf (file, " %2ld %14s %08lx %08lx %08lx\n",
2641 idd.Type, type_name, idd.SizeOfData,
2642 idd.AddressOfRawData, idd.PointerToRawData);
2644 if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
2646 char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
2647 /* PR 17512: file: 065-29434-0.001:0.1
2648 We need to use a 32-bit aligned buffer
2649 to safely read in a codeview record. */
2650 char buffer[256 + 1] ATTRIBUTE_ALIGNED_ALIGNOF (CODEVIEW_INFO);
2651 char *pdb;
2653 CODEVIEW_INFO *cvinfo = (CODEVIEW_INFO *) buffer;
2655 /* The debug entry doesn't have to have to be in a section,
2656 in which case AddressOfRawData is 0, so always use PointerToRawData. */
2657 if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
2658 idd.SizeOfData, cvinfo, &pdb))
2659 continue;
2661 for (j = 0; j < cvinfo->SignatureLength; j++)
2662 sprintf (&signature[j*2], "%02x", cvinfo->Signature[j] & 0xff);
2664 /* xgettext:c-format */
2665 fprintf (file, _("(format %c%c%c%c signature %s age %ld pdb %s)\n"),
2666 buffer[0], buffer[1], buffer[2], buffer[3],
2667 signature, cvinfo->Age, pdb[0] ? pdb : "(none)");
2669 free (pdb);
2673 free(data);
2675 if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
2676 fprintf (file,
2677 _("The debug directory size is not a multiple of the debug directory entry size\n"));
2679 return true;
2682 static bool
2683 pe_is_repro (bfd * abfd)
2685 pe_data_type *pe = pe_data (abfd);
2686 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2687 asection *section;
2688 bfd_byte *data = 0;
2689 bfd_size_type dataoff;
2690 unsigned int i;
2691 bool res = false;
2693 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2694 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2696 if (size == 0)
2697 return false;
2699 addr += extra->ImageBase;
2700 for (section = abfd->sections; section != NULL; section = section->next)
2702 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2703 break;
2706 if ((section == NULL)
2707 || (!(section->flags & SEC_HAS_CONTENTS))
2708 || (section->size < size))
2710 return false;
2713 dataoff = addr - section->vma;
2715 if (size > (section->size - dataoff))
2717 return false;
2720 if (!bfd_malloc_and_get_section (abfd, section, &data))
2722 free (data);
2723 return false;
2726 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2728 struct external_IMAGE_DEBUG_DIRECTORY *ext
2729 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2730 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2732 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2734 if (idd.Type == PE_IMAGE_DEBUG_TYPE_REPRO)
2736 res = true;
2737 break;
2741 free(data);
2743 return res;
2746 /* Print out the program headers. */
2748 bool
2749 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
2751 FILE *file = (FILE *) vfile;
2752 int j;
2753 pe_data_type *pe = pe_data (abfd);
2754 struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
2755 const char *subsystem_name = NULL;
2756 const char *name;
2758 /* The MS dumpbin program reportedly ands with 0xff0f before
2759 printing the characteristics field. Not sure why. No reason to
2760 emulate it here. */
2761 fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
2762 #undef PF
2763 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
2764 PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
2765 PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
2766 PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
2767 PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
2768 PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
2769 PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
2770 PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
2771 PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
2772 PF (IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "copy to swap file if on removable media");
2773 PF (IMAGE_FILE_NET_RUN_FROM_SWAP, "copy to swap file if on network media");
2774 PF (IMAGE_FILE_SYSTEM, "system file");
2775 PF (IMAGE_FILE_DLL, "DLL");
2776 PF (IMAGE_FILE_UP_SYSTEM_ONLY, "run only on uniprocessor machine");
2777 PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
2778 #undef PF
2781 If a PE_IMAGE_DEBUG_TYPE_REPRO entry is present in the debug directory, the
2782 timestamp is to be interpreted as the hash of a reproducible build.
2784 if (pe_is_repro (abfd))
2786 fprintf (file, "\nTime/Date\t\t%08lx", pe->coff.timestamp);
2787 fprintf (file, "\t(This is a reproducible build file hash, not a timestamp)\n");
2789 else
2791 /* ctime implies '\n'. */
2792 time_t t = pe->coff.timestamp;
2793 fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
2796 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
2797 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
2798 #endif
2799 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
2800 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
2801 #endif
2802 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
2803 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
2804 #endif
2806 switch (i->Magic)
2808 case IMAGE_NT_OPTIONAL_HDR_MAGIC:
2809 name = "PE32";
2810 break;
2811 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
2812 name = "PE32+";
2813 break;
2814 case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
2815 name = "ROM";
2816 break;
2817 default:
2818 name = NULL;
2819 break;
2821 fprintf (file, "Magic\t\t\t%04x", i->Magic);
2822 if (name)
2823 fprintf (file, "\t(%s)",name);
2824 fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
2825 fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
2826 fprintf (file, "SizeOfCode\t\t");
2827 bfd_fprintf_vma (abfd, file, i->SizeOfCode);
2828 fprintf (file, "\nSizeOfInitializedData\t");
2829 bfd_fprintf_vma (abfd, file, i->SizeOfInitializedData);
2830 fprintf (file, "\nSizeOfUninitializedData\t");
2831 bfd_fprintf_vma (abfd, file, i->SizeOfUninitializedData);
2832 fprintf (file, "\nAddressOfEntryPoint\t");
2833 bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
2834 fprintf (file, "\nBaseOfCode\t\t");
2835 bfd_fprintf_vma (abfd, file, i->BaseOfCode);
2836 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
2837 /* PE32+ does not have BaseOfData member! */
2838 fprintf (file, "\nBaseOfData\t\t");
2839 bfd_fprintf_vma (abfd, file, i->BaseOfData);
2840 #endif
2842 fprintf (file, "\nImageBase\t\t");
2843 bfd_fprintf_vma (abfd, file, i->ImageBase);
2844 fprintf (file, "\nSectionAlignment\t%08x\n", i->SectionAlignment);
2845 fprintf (file, "FileAlignment\t\t%08x\n", i->FileAlignment);
2846 fprintf (file, "MajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
2847 fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
2848 fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
2849 fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
2850 fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
2851 fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
2852 fprintf (file, "Win32Version\t\t%08x\n", i->Win32Version);
2853 fprintf (file, "SizeOfImage\t\t%08x\n", i->SizeOfImage);
2854 fprintf (file, "SizeOfHeaders\t\t%08x\n", i->SizeOfHeaders);
2855 fprintf (file, "CheckSum\t\t%08x\n", i->CheckSum);
2857 switch (i->Subsystem)
2859 case IMAGE_SUBSYSTEM_UNKNOWN:
2860 subsystem_name = "unspecified";
2861 break;
2862 case IMAGE_SUBSYSTEM_NATIVE:
2863 subsystem_name = "NT native";
2864 break;
2865 case IMAGE_SUBSYSTEM_WINDOWS_GUI:
2866 subsystem_name = "Windows GUI";
2867 break;
2868 case IMAGE_SUBSYSTEM_WINDOWS_CUI:
2869 subsystem_name = "Windows CUI";
2870 break;
2871 case IMAGE_SUBSYSTEM_POSIX_CUI:
2872 subsystem_name = "POSIX CUI";
2873 break;
2874 case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
2875 subsystem_name = "Wince CUI";
2876 break;
2877 /* These are from UEFI Platform Initialization Specification 1.1. */
2878 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
2879 subsystem_name = "EFI application";
2880 break;
2881 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
2882 subsystem_name = "EFI boot service driver";
2883 break;
2884 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
2885 subsystem_name = "EFI runtime driver";
2886 break;
2887 case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
2888 subsystem_name = "SAL runtime driver";
2889 break;
2890 /* This is from revision 8.0 of the MS PE/COFF spec */
2891 case IMAGE_SUBSYSTEM_XBOX:
2892 subsystem_name = "XBOX";
2893 break;
2894 /* Added default case for clarity - subsystem_name is NULL anyway. */
2895 default:
2896 subsystem_name = NULL;
2899 fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
2900 if (subsystem_name)
2901 fprintf (file, "\t(%s)", subsystem_name);
2902 fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
2903 if (i->DllCharacteristics)
2905 unsigned short dllch = i->DllCharacteristics;
2906 const char *indent = "\t\t\t\t\t";
2908 if (dllch & IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA)
2909 fprintf (file, "%sHIGH_ENTROPY_VA\n", indent);
2910 if (dllch & IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE)
2911 fprintf (file, "%sDYNAMIC_BASE\n", indent);
2912 if (dllch & IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY)
2913 fprintf (file, "%sFORCE_INTEGRITY\n", indent);
2914 if (dllch & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT)
2915 fprintf (file, "%sNX_COMPAT\n", indent);
2916 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_ISOLATION)
2917 fprintf (file, "%sNO_ISOLATION\n", indent);
2918 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_SEH)
2919 fprintf (file, "%sNO_SEH\n", indent);
2920 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_BIND)
2921 fprintf (file, "%sNO_BIND\n", indent);
2922 if (dllch & IMAGE_DLLCHARACTERISTICS_APPCONTAINER)
2923 fprintf (file, "%sAPPCONTAINER\n", indent);
2924 if (dllch & IMAGE_DLLCHARACTERISTICS_WDM_DRIVER)
2925 fprintf (file, "%sWDM_DRIVER\n", indent);
2926 if (dllch & IMAGE_DLLCHARACTERISTICS_GUARD_CF)
2927 fprintf (file, "%sGUARD_CF\n", indent);
2928 if (dllch & IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE)
2929 fprintf (file, "%sTERMINAL_SERVICE_AWARE\n", indent);
2931 fprintf (file, "SizeOfStackReserve\t");
2932 bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
2933 fprintf (file, "\nSizeOfStackCommit\t");
2934 bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
2935 fprintf (file, "\nSizeOfHeapReserve\t");
2936 bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
2937 fprintf (file, "\nSizeOfHeapCommit\t");
2938 bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
2939 fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
2940 fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
2941 (unsigned long) i->NumberOfRvaAndSizes);
2943 fprintf (file, "\nThe Data Directory\n");
2944 for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
2946 fprintf (file, "Entry %1x ", j);
2947 bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
2948 fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
2949 fprintf (file, "%s\n", dir_names[j]);
2952 pe_print_idata (abfd, vfile);
2953 pe_print_edata (abfd, vfile);
2954 if (bfd_coff_have_print_pdata (abfd))
2955 bfd_coff_print_pdata (abfd, vfile);
2956 else
2957 pe_print_pdata (abfd, vfile);
2958 pe_print_reloc (abfd, vfile);
2959 pe_print_debugdata (abfd, file);
2961 rsrc_print_section (abfd, vfile);
2963 return true;
2966 static bool
2967 is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
2969 bfd_vma addr = * (bfd_vma *) obj;
2970 return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
2973 static asection *
2974 find_section_by_vma (bfd *abfd, bfd_vma addr)
2976 return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
2979 /* Copy any private info we understand from the input bfd
2980 to the output bfd. */
2982 bool
2983 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
2985 pe_data_type *ipe, *ope;
2986 bfd_size_type size;
2988 /* One day we may try to grok other private data. */
2989 if (ibfd->xvec->flavour != bfd_target_coff_flavour
2990 || obfd->xvec->flavour != bfd_target_coff_flavour)
2991 return true;
2993 ipe = pe_data (ibfd);
2994 ope = pe_data (obfd);
2996 /* pe_opthdr is copied in copy_object. */
2997 ope->dll = ipe->dll;
2999 /* Don't copy input subsystem if output is different from input. */
3000 if (obfd->xvec != ibfd->xvec)
3001 ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
3003 /* For strip: if we removed .reloc, we'll make a real mess of things
3004 if we don't remove this entry as well. */
3005 if (! pe_data (obfd)->has_reloc_section)
3007 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
3008 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
3011 /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
3012 But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
3013 won't be added. */
3014 if (! pe_data (ibfd)->has_reloc_section
3015 && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
3016 pe_data (obfd)->dont_strip_reloc = 1;
3018 memcpy (ope->dos_message, ipe->dos_message, sizeof (ope->dos_message));
3020 /* The file offsets contained in the debug directory need rewriting. */
3021 size = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size;
3022 if (size != 0)
3024 bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
3025 + ope->pe_opthdr.ImageBase;
3026 /* In particular a .buildid section may overlap (in VA space) with
3027 whatever section comes ahead of it (largely because of section->size
3028 representing s_size, not virt_size). Therefore don't look for the
3029 section containing the first byte, but for that covering the last
3030 one. */
3031 bfd_vma last = addr + size - 1;
3032 asection *section = find_section_by_vma (obfd, last);
3034 if (section != NULL)
3036 bfd_byte *data;
3037 bfd_vma dataoff = addr - section->vma;
3039 /* PR 17512: file: 0f15796a. */
3040 if (addr < section->vma
3041 || section->size < dataoff
3042 || section->size - dataoff < size)
3044 /* xgettext:c-format */
3045 _bfd_error_handler
3046 (_("%pB: Data Directory (%lx bytes at %" PRIx64 ") "
3047 "extends across section boundary at %" PRIx64),
3048 obfd, ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size,
3049 (uint64_t) addr, (uint64_t) section->vma);
3050 return false;
3053 if ((section->flags & SEC_HAS_CONTENTS) != 0
3054 && bfd_malloc_and_get_section (obfd, section, &data))
3056 unsigned int i;
3057 struct external_IMAGE_DEBUG_DIRECTORY *dd =
3058 (struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff);
3060 for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
3061 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
3063 asection *ddsection;
3064 struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
3065 struct internal_IMAGE_DEBUG_DIRECTORY idd;
3066 bfd_vma idd_vma;
3068 _bfd_XXi_swap_debugdir_in (obfd, edd, &idd);
3070 /* RVA 0 means only offset is valid, not handled yet. */
3071 if (idd.AddressOfRawData == 0)
3072 continue;
3074 idd_vma = idd.AddressOfRawData + ope->pe_opthdr.ImageBase;
3075 ddsection = find_section_by_vma (obfd, idd_vma);
3076 if (!ddsection)
3077 continue; /* Not in a section! */
3079 idd.PointerToRawData
3080 = ddsection->filepos + idd_vma - ddsection->vma;
3081 _bfd_XXi_swap_debugdir_out (obfd, &idd, edd);
3084 if (!bfd_set_section_contents (obfd, section, data, 0,
3085 section->size))
3087 _bfd_error_handler (_("failed to update file offsets"
3088 " in debug directory"));
3089 free (data);
3090 return false;
3092 free (data);
3094 else
3096 _bfd_error_handler (_("%pB: failed to read "
3097 "debug data section"), obfd);
3098 return false;
3103 return true;
3106 /* Copy private section data. */
3108 bool
3109 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
3110 asection *isec,
3111 bfd *obfd,
3112 asection *osec)
3114 if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
3115 || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
3116 return true;
3118 if (coff_section_data (ibfd, isec) != NULL
3119 && pei_section_data (ibfd, isec) != NULL)
3121 if (coff_section_data (obfd, osec) == NULL)
3123 size_t amt = sizeof (struct coff_section_tdata);
3124 osec->used_by_bfd = bfd_zalloc (obfd, amt);
3125 if (osec->used_by_bfd == NULL)
3126 return false;
3129 if (pei_section_data (obfd, osec) == NULL)
3131 size_t amt = sizeof (struct pei_section_tdata);
3132 coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
3133 if (coff_section_data (obfd, osec)->tdata == NULL)
3134 return false;
3137 pei_section_data (obfd, osec)->virt_size =
3138 pei_section_data (ibfd, isec)->virt_size;
3139 pei_section_data (obfd, osec)->pe_flags =
3140 pei_section_data (ibfd, isec)->pe_flags;
3143 return true;
3146 void
3147 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
3149 coff_get_symbol_info (abfd, symbol, ret);
3152 #if !defined(COFF_WITH_pep) && (defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64))
3153 static int
3154 sort_x64_pdata (const void *l, const void *r)
3156 const char *lp = (const char *) l;
3157 const char *rp = (const char *) r;
3158 bfd_vma vl, vr;
3159 vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
3160 if (vl != vr)
3161 return (vl < vr ? -1 : 1);
3162 /* We compare just begin address. */
3163 return 0;
3165 #endif
3167 /* Functions to process a .rsrc section. */
3169 static unsigned int sizeof_leaves;
3170 static unsigned int sizeof_strings;
3171 static unsigned int sizeof_tables_and_entries;
3173 static bfd_byte *
3174 rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
3176 static bfd_byte *
3177 rsrc_count_entries (bfd *abfd,
3178 bool is_name,
3179 bfd_byte *datastart,
3180 bfd_byte *data,
3181 bfd_byte *dataend,
3182 bfd_vma rva_bias)
3184 unsigned long entry, addr, size;
3186 if (data + 8 >= dataend)
3187 return dataend + 1;
3189 if (is_name)
3191 bfd_byte * name;
3193 entry = (long) bfd_get_32 (abfd, data);
3195 if (HighBitSet (entry))
3196 name = datastart + WithoutHighBit (entry);
3197 else
3198 name = datastart + entry - rva_bias;
3200 if (name + 2 >= dataend || name < datastart)
3201 return dataend + 1;
3203 unsigned int len = bfd_get_16 (abfd, name);
3204 if (len == 0 || len > 256)
3205 return dataend + 1;
3208 entry = (long) bfd_get_32 (abfd, data + 4);
3210 if (HighBitSet (entry))
3212 data = datastart + WithoutHighBit (entry);
3214 if (data <= datastart || data >= dataend)
3215 return dataend + 1;
3217 return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
3220 if (datastart + entry + 16 >= dataend)
3221 return dataend + 1;
3223 addr = (long) bfd_get_32 (abfd, datastart + entry);
3224 size = (long) bfd_get_32 (abfd, datastart + entry + 4);
3226 return datastart + addr - rva_bias + size;
3229 static bfd_byte *
3230 rsrc_count_directory (bfd * abfd,
3231 bfd_byte * datastart,
3232 bfd_byte * data,
3233 bfd_byte * dataend,
3234 bfd_vma rva_bias)
3236 unsigned int num_entries, num_ids;
3237 bfd_byte * highest_data = data;
3239 if (data + 16 >= dataend)
3240 return dataend + 1;
3242 num_entries = (int) bfd_get_16 (abfd, data + 12);
3243 num_ids = (int) bfd_get_16 (abfd, data + 14);
3245 num_entries += num_ids;
3247 data += 16;
3249 while (num_entries --)
3251 bfd_byte * entry_end;
3253 entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
3254 datastart, data, dataend, rva_bias);
3255 data += 8;
3256 highest_data = max (highest_data, entry_end);
3257 if (entry_end >= dataend)
3258 break;
3261 return max (highest_data, data);
3264 typedef struct rsrc_dir_chain
3266 unsigned int num_entries;
3267 struct rsrc_entry * first_entry;
3268 struct rsrc_entry * last_entry;
3269 } rsrc_dir_chain;
3271 typedef struct rsrc_directory
3273 unsigned int characteristics;
3274 unsigned int time;
3275 unsigned int major;
3276 unsigned int minor;
3278 rsrc_dir_chain names;
3279 rsrc_dir_chain ids;
3281 struct rsrc_entry * entry;
3282 } rsrc_directory;
3284 typedef struct rsrc_string
3286 unsigned int len;
3287 bfd_byte * string;
3288 } rsrc_string;
3290 typedef struct rsrc_leaf
3292 unsigned int size;
3293 unsigned int codepage;
3294 bfd_byte * data;
3295 } rsrc_leaf;
3297 typedef struct rsrc_entry
3299 bool is_name;
3300 union
3302 unsigned int id;
3303 struct rsrc_string name;
3304 } name_id;
3306 bool is_dir;
3307 union
3309 struct rsrc_directory * directory;
3310 struct rsrc_leaf * leaf;
3311 } value;
3313 struct rsrc_entry * next_entry;
3314 struct rsrc_directory * parent;
3315 } rsrc_entry;
3317 static bfd_byte *
3318 rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
3319 bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
3321 static bfd_byte *
3322 rsrc_parse_entry (bfd *abfd,
3323 bool is_name,
3324 rsrc_entry *entry,
3325 bfd_byte *datastart,
3326 bfd_byte * data,
3327 bfd_byte *dataend,
3328 bfd_vma rva_bias,
3329 rsrc_directory *parent)
3331 unsigned long val, addr, size;
3333 val = bfd_get_32 (abfd, data);
3335 entry->parent = parent;
3336 entry->is_name = is_name;
3338 if (is_name)
3340 bfd_byte * address;
3342 if (HighBitSet (val))
3344 val = WithoutHighBit (val);
3346 address = datastart + val;
3348 else
3350 address = datastart + val - rva_bias;
3353 if (address + 3 > dataend)
3354 return dataend;
3356 entry->name_id.name.len = bfd_get_16 (abfd, address);
3357 entry->name_id.name.string = address + 2;
3359 else
3360 entry->name_id.id = val;
3362 val = bfd_get_32 (abfd, data + 4);
3364 if (HighBitSet (val))
3366 entry->is_dir = true;
3367 entry->value.directory = bfd_malloc (sizeof (*entry->value.directory));
3368 if (entry->value.directory == NULL)
3369 return dataend;
3371 return rsrc_parse_directory (abfd, entry->value.directory,
3372 datastart,
3373 datastart + WithoutHighBit (val),
3374 dataend, rva_bias, entry);
3377 entry->is_dir = false;
3378 entry->value.leaf = bfd_malloc (sizeof (*entry->value.leaf));
3379 if (entry->value.leaf == NULL)
3380 return dataend;
3382 data = datastart + val;
3383 if (data < datastart || data + 12 > dataend)
3384 return dataend;
3386 addr = bfd_get_32 (abfd, data);
3387 size = entry->value.leaf->size = bfd_get_32 (abfd, data + 4);
3388 entry->value.leaf->codepage = bfd_get_32 (abfd, data + 8);
3389 /* FIXME: We assume that the reserved field (data + 12) is OK. */
3391 if (size > dataend - datastart - (addr - rva_bias))
3392 return dataend;
3393 entry->value.leaf->data = bfd_malloc (size);
3394 if (entry->value.leaf->data == NULL)
3395 return dataend;
3397 memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
3398 return datastart + (addr - rva_bias) + size;
3401 static bfd_byte *
3402 rsrc_parse_entries (bfd *abfd,
3403 rsrc_dir_chain *chain,
3404 bool is_name,
3405 bfd_byte *highest_data,
3406 bfd_byte *datastart,
3407 bfd_byte *data,
3408 bfd_byte *dataend,
3409 bfd_vma rva_bias,
3410 rsrc_directory *parent)
3412 unsigned int i;
3413 rsrc_entry * entry;
3415 if (chain->num_entries == 0)
3417 chain->first_entry = chain->last_entry = NULL;
3418 return highest_data;
3421 entry = bfd_malloc (sizeof (*entry));
3422 if (entry == NULL)
3423 return dataend;
3425 chain->first_entry = entry;
3427 for (i = chain->num_entries; i--;)
3429 bfd_byte * entry_end;
3431 entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
3432 data, dataend, rva_bias, parent);
3433 data += 8;
3434 highest_data = max (entry_end, highest_data);
3435 if (entry_end > dataend)
3436 return dataend;
3438 if (i)
3440 entry->next_entry = bfd_malloc (sizeof (*entry));
3441 entry = entry->next_entry;
3442 if (entry == NULL)
3443 return dataend;
3445 else
3446 entry->next_entry = NULL;
3449 chain->last_entry = entry;
3451 return highest_data;
3454 static bfd_byte *
3455 rsrc_parse_directory (bfd * abfd,
3456 rsrc_directory * table,
3457 bfd_byte * datastart,
3458 bfd_byte * data,
3459 bfd_byte * dataend,
3460 bfd_vma rva_bias,
3461 rsrc_entry * entry)
3463 bfd_byte * highest_data = data;
3465 if (table == NULL)
3466 return dataend;
3468 table->characteristics = bfd_get_32 (abfd, data);
3469 table->time = bfd_get_32 (abfd, data + 4);
3470 table->major = bfd_get_16 (abfd, data + 8);
3471 table->minor = bfd_get_16 (abfd, data + 10);
3472 table->names.num_entries = bfd_get_16 (abfd, data + 12);
3473 table->ids.num_entries = bfd_get_16 (abfd, data + 14);
3474 table->entry = entry;
3476 data += 16;
3478 highest_data = rsrc_parse_entries (abfd, & table->names, true, data,
3479 datastart, data, dataend, rva_bias, table);
3480 data += table->names.num_entries * 8;
3482 highest_data = rsrc_parse_entries (abfd, & table->ids, false, highest_data,
3483 datastart, data, dataend, rva_bias, table);
3484 data += table->ids.num_entries * 8;
3486 return max (highest_data, data);
3489 typedef struct rsrc_write_data
3491 bfd * abfd;
3492 bfd_byte * datastart;
3493 bfd_byte * next_table;
3494 bfd_byte * next_leaf;
3495 bfd_byte * next_string;
3496 bfd_byte * next_data;
3497 bfd_vma rva_bias;
3498 } rsrc_write_data;
3500 static void
3501 rsrc_write_string (rsrc_write_data * data,
3502 rsrc_string * string)
3504 bfd_put_16 (data->abfd, string->len, data->next_string);
3505 memcpy (data->next_string + 2, string->string, string->len * 2);
3506 data->next_string += (string->len + 1) * 2;
3509 static inline unsigned int
3510 rsrc_compute_rva (rsrc_write_data * data,
3511 bfd_byte * addr)
3513 return (addr - data->datastart) + data->rva_bias;
3516 static void
3517 rsrc_write_leaf (rsrc_write_data * data,
3518 rsrc_leaf * leaf)
3520 bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
3521 data->next_leaf);
3522 bfd_put_32 (data->abfd, leaf->size, data->next_leaf + 4);
3523 bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
3524 bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
3525 data->next_leaf += 16;
3527 memcpy (data->next_data, leaf->data, leaf->size);
3528 /* An undocumented feature of Windows resources is that each unit
3529 of raw data is 8-byte aligned... */
3530 data->next_data += ((leaf->size + 7) & ~7);
3533 static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
3535 static void
3536 rsrc_write_entry (rsrc_write_data * data,
3537 bfd_byte * where,
3538 rsrc_entry * entry)
3540 if (entry->is_name)
3542 bfd_put_32 (data->abfd,
3543 SetHighBit (data->next_string - data->datastart),
3544 where);
3545 rsrc_write_string (data, & entry->name_id.name);
3547 else
3548 bfd_put_32 (data->abfd, entry->name_id.id, where);
3550 if (entry->is_dir)
3552 bfd_put_32 (data->abfd,
3553 SetHighBit (data->next_table - data->datastart),
3554 where + 4);
3555 rsrc_write_directory (data, entry->value.directory);
3557 else
3559 bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
3560 rsrc_write_leaf (data, entry->value.leaf);
3564 static void
3565 rsrc_compute_region_sizes (rsrc_directory * dir)
3567 struct rsrc_entry * entry;
3569 if (dir == NULL)
3570 return;
3572 sizeof_tables_and_entries += 16;
3574 for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
3576 sizeof_tables_and_entries += 8;
3578 sizeof_strings += (entry->name_id.name.len + 1) * 2;
3580 if (entry->is_dir)
3581 rsrc_compute_region_sizes (entry->value.directory);
3582 else
3583 sizeof_leaves += 16;
3586 for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
3588 sizeof_tables_and_entries += 8;
3590 if (entry->is_dir)
3591 rsrc_compute_region_sizes (entry->value.directory);
3592 else
3593 sizeof_leaves += 16;
3597 static void
3598 rsrc_write_directory (rsrc_write_data * data,
3599 rsrc_directory * dir)
3601 rsrc_entry * entry;
3602 unsigned int i;
3603 bfd_byte * next_entry;
3604 bfd_byte * nt;
3606 bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
3607 bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
3608 bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
3609 bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
3610 bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
3611 bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
3613 /* Compute where the entries and the next table will be placed. */
3614 next_entry = data->next_table + 16;
3615 data->next_table = next_entry + (dir->names.num_entries * 8)
3616 + (dir->ids.num_entries * 8);
3617 nt = data->next_table;
3619 /* Write the entries. */
3620 for (i = dir->names.num_entries, entry = dir->names.first_entry;
3621 i > 0 && entry != NULL;
3622 i--, entry = entry->next_entry)
3624 BFD_ASSERT (entry->is_name);
3625 rsrc_write_entry (data, next_entry, entry);
3626 next_entry += 8;
3628 BFD_ASSERT (i == 0);
3629 BFD_ASSERT (entry == NULL);
3631 for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
3632 i > 0 && entry != NULL;
3633 i--, entry = entry->next_entry)
3635 BFD_ASSERT (! entry->is_name);
3636 rsrc_write_entry (data, next_entry, entry);
3637 next_entry += 8;
3639 BFD_ASSERT (i == 0);
3640 BFD_ASSERT (entry == NULL);
3641 BFD_ASSERT (nt == next_entry);
3644 #if ! defined __CYGWIN__ && ! defined __MINGW32__
3645 /* Return the length (number of units) of the first character in S,
3646 putting its 'ucs4_t' representation in *PUC. */
3648 static unsigned int
3649 u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
3651 unsigned short c = * s;
3653 if (c < 0xd800 || c >= 0xe000)
3655 *puc = c;
3656 return 1;
3659 if (c < 0xdc00)
3661 if (n >= 2)
3663 if (s[1] >= 0xdc00 && s[1] < 0xe000)
3665 *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
3666 return 2;
3669 else
3671 /* Incomplete multibyte character. */
3672 *puc = 0xfffd;
3673 return n;
3677 /* Invalid multibyte character. */
3678 *puc = 0xfffd;
3679 return 1;
3681 #endif /* not Cygwin/Mingw */
3683 /* Perform a comparison of two entries. */
3684 static signed int
3685 rsrc_cmp (bool is_name, rsrc_entry * a, rsrc_entry * b)
3687 signed int res;
3688 bfd_byte * astring;
3689 unsigned int alen;
3690 bfd_byte * bstring;
3691 unsigned int blen;
3693 if (! is_name)
3694 return a->name_id.id - b->name_id.id;
3696 /* We have to perform a case insenstive, unicode string comparison... */
3697 astring = a->name_id.name.string;
3698 alen = a->name_id.name.len;
3699 bstring = b->name_id.name.string;
3700 blen = b->name_id.name.len;
3702 #if defined __CYGWIN__ || defined __MINGW32__
3703 /* Under Windows hosts (both Cygwin and Mingw types),
3704 unicode == UTF-16 == wchar_t. The case insensitive string comparison
3705 function however goes by different names in the two environments... */
3707 #undef rscpcmp
3708 #ifdef __CYGWIN__
3709 #define rscpcmp wcsncasecmp
3710 #endif
3711 #ifdef __MINGW32__
3712 #define rscpcmp wcsnicmp
3713 #endif
3715 res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
3716 min (alen, blen));
3718 #else
3720 unsigned int i;
3722 res = 0;
3723 for (i = min (alen, blen); i--; astring += 2, bstring += 2)
3725 wint_t awc;
3726 wint_t bwc;
3728 /* Convert UTF-16 unicode characters into wchar_t characters
3729 so that we can then perform a case insensitive comparison. */
3730 unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
3731 unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
3733 if (Alen != Blen)
3734 return Alen - Blen;
3736 awc = towlower (awc);
3737 bwc = towlower (bwc);
3739 res = awc - bwc;
3740 if (res)
3741 break;
3744 #endif
3746 if (res == 0)
3747 res = alen - blen;
3749 return res;
3752 static void
3753 rsrc_print_name (char * buffer, rsrc_string string)
3755 unsigned int i;
3756 bfd_byte * name = string.string;
3758 for (i = string.len; i--; name += 2)
3759 sprintf (buffer + strlen (buffer), "%.1s", name);
3762 static const char *
3763 rsrc_resource_name (rsrc_entry *entry, rsrc_directory *dir, char *buffer)
3765 bool is_string = false;
3767 buffer[0] = 0;
3769 if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
3770 && dir->entry->parent->entry != NULL)
3772 strcpy (buffer, "type: ");
3773 if (dir->entry->parent->entry->is_name)
3774 rsrc_print_name (buffer + strlen (buffer),
3775 dir->entry->parent->entry->name_id.name);
3776 else
3778 unsigned int id = dir->entry->parent->entry->name_id.id;
3780 sprintf (buffer + strlen (buffer), "%x", id);
3781 switch (id)
3783 case 1: strcat (buffer, " (CURSOR)"); break;
3784 case 2: strcat (buffer, " (BITMAP)"); break;
3785 case 3: strcat (buffer, " (ICON)"); break;
3786 case 4: strcat (buffer, " (MENU)"); break;
3787 case 5: strcat (buffer, " (DIALOG)"); break;
3788 case 6: strcat (buffer, " (STRING)"); is_string = true; break;
3789 case 7: strcat (buffer, " (FONTDIR)"); break;
3790 case 8: strcat (buffer, " (FONT)"); break;
3791 case 9: strcat (buffer, " (ACCELERATOR)"); break;
3792 case 10: strcat (buffer, " (RCDATA)"); break;
3793 case 11: strcat (buffer, " (MESSAGETABLE)"); break;
3794 case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
3795 case 14: strcat (buffer, " (GROUP_ICON)"); break;
3796 case 16: strcat (buffer, " (VERSION)"); break;
3797 case 17: strcat (buffer, " (DLGINCLUDE)"); break;
3798 case 19: strcat (buffer, " (PLUGPLAY)"); break;
3799 case 20: strcat (buffer, " (VXD)"); break;
3800 case 21: strcat (buffer, " (ANICURSOR)"); break;
3801 case 22: strcat (buffer, " (ANIICON)"); break;
3802 case 23: strcat (buffer, " (HTML)"); break;
3803 case 24: strcat (buffer, " (MANIFEST)"); break;
3804 case 240: strcat (buffer, " (DLGINIT)"); break;
3805 case 241: strcat (buffer, " (TOOLBAR)"); break;
3810 if (dir != NULL && dir->entry != NULL)
3812 strcat (buffer, " name: ");
3813 if (dir->entry->is_name)
3814 rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
3815 else
3817 unsigned int id = dir->entry->name_id.id;
3819 sprintf (buffer + strlen (buffer), "%x", id);
3821 if (is_string)
3822 sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
3823 (id - 1) << 4, (id << 4) - 1);
3827 if (entry != NULL)
3829 strcat (buffer, " lang: ");
3831 if (entry->is_name)
3832 rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
3833 else
3834 sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
3837 return buffer;
3840 /* *sigh* Windows resource strings are special. Only the top 28-bits of
3841 their ID is stored in the NAME entry. The bottom four bits are used as
3842 an index into unicode string table that makes up the data of the leaf.
3843 So identical type-name-lang string resources may not actually be
3844 identical at all.
3846 This function is called when we have detected two string resources with
3847 match top-28-bit IDs. We have to scan the string tables inside the leaves
3848 and discover if there are any real collisions. If there are then we report
3849 them and return FALSE. Otherwise we copy any strings from B into A and
3850 then return TRUE. */
3852 static bool
3853 rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
3854 rsrc_entry * b ATTRIBUTE_UNUSED)
3856 unsigned int copy_needed = 0;
3857 unsigned int i;
3858 bfd_byte * astring;
3859 bfd_byte * bstring;
3860 bfd_byte * new_data;
3861 bfd_byte * nstring;
3863 /* Step one: Find out what we have to do. */
3864 BFD_ASSERT (! a->is_dir);
3865 astring = a->value.leaf->data;
3867 BFD_ASSERT (! b->is_dir);
3868 bstring = b->value.leaf->data;
3870 for (i = 0; i < 16; i++)
3872 unsigned int alen = astring[0] + (astring[1] << 8);
3873 unsigned int blen = bstring[0] + (bstring[1] << 8);
3875 if (alen == 0)
3877 copy_needed += blen * 2;
3879 else if (blen == 0)
3881 else if (alen != blen)
3882 /* FIXME: Should we continue the loop in order to report other duplicates ? */
3883 break;
3884 /* alen == blen != 0. We might have two identical strings. If so we
3885 can ignore the second one. There is no need for wchar_t vs UTF-16
3886 theatrics here - we are only interested in (case sensitive) equality. */
3887 else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
3888 break;
3890 astring += (alen + 1) * 2;
3891 bstring += (blen + 1) * 2;
3894 if (i != 16)
3896 if (a->parent != NULL
3897 && a->parent->entry != NULL
3898 && !a->parent->entry->is_name)
3899 _bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
3900 ((a->parent->entry->name_id.id - 1) << 4) + i);
3901 return false;
3904 if (copy_needed == 0)
3905 return true;
3907 /* If we reach here then A and B must both have non-colliding strings.
3908 (We never get string resources with fully empty string tables).
3909 We need to allocate an extra COPY_NEEDED bytes in A and then bring
3910 in B's strings. */
3911 new_data = bfd_malloc (a->value.leaf->size + copy_needed);
3912 if (new_data == NULL)
3913 return false;
3915 nstring = new_data;
3916 astring = a->value.leaf->data;
3917 bstring = b->value.leaf->data;
3919 for (i = 0; i < 16; i++)
3921 unsigned int alen = astring[0] + (astring[1] << 8);
3922 unsigned int blen = bstring[0] + (bstring[1] << 8);
3924 if (alen != 0)
3926 memcpy (nstring, astring, (alen + 1) * 2);
3927 nstring += (alen + 1) * 2;
3929 else if (blen != 0)
3931 memcpy (nstring, bstring, (blen + 1) * 2);
3932 nstring += (blen + 1) * 2;
3934 else
3936 * nstring++ = 0;
3937 * nstring++ = 0;
3940 astring += (alen + 1) * 2;
3941 bstring += (blen + 1) * 2;
3944 BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
3946 free (a->value.leaf->data);
3947 a->value.leaf->data = new_data;
3948 a->value.leaf->size += copy_needed;
3950 return true;
3953 static void rsrc_merge (rsrc_entry *, rsrc_entry *);
3955 /* Sort the entries in given part of the directory.
3956 We use an old fashioned bubble sort because we are dealing
3957 with lists and we want to handle matches specially. */
3959 static void
3960 rsrc_sort_entries (rsrc_dir_chain *chain,
3961 bool is_name,
3962 rsrc_directory *dir)
3964 rsrc_entry * entry;
3965 rsrc_entry * next;
3966 rsrc_entry ** points_to_entry;
3967 bool swapped;
3969 if (chain->num_entries < 2)
3970 return;
3974 swapped = false;
3975 points_to_entry = & chain->first_entry;
3976 entry = * points_to_entry;
3977 next = entry->next_entry;
3981 signed int cmp = rsrc_cmp (is_name, entry, next);
3983 if (cmp > 0)
3985 entry->next_entry = next->next_entry;
3986 next->next_entry = entry;
3987 * points_to_entry = next;
3988 points_to_entry = & next->next_entry;
3989 next = entry->next_entry;
3990 swapped = true;
3992 else if (cmp == 0)
3994 if (entry->is_dir && next->is_dir)
3996 /* When we encounter identical directory entries we have to
3997 merge them together. The exception to this rule is for
3998 resource manifests - there can only be one of these,
3999 even if they differ in language. Zero-language manifests
4000 are assumed to be default manifests (provided by the
4001 Cygwin/MinGW build system) and these can be silently dropped,
4002 unless that would reduce the number of manifests to zero.
4003 There should only ever be one non-zero lang manifest -
4004 if there are more it is an error. A non-zero lang
4005 manifest takes precedence over a default manifest. */
4006 if (!entry->is_name
4007 && entry->name_id.id == 1
4008 && dir != NULL
4009 && dir->entry != NULL
4010 && !dir->entry->is_name
4011 && dir->entry->name_id.id == 0x18)
4013 if (next->value.directory->names.num_entries == 0
4014 && next->value.directory->ids.num_entries == 1
4015 && !next->value.directory->ids.first_entry->is_name
4016 && next->value.directory->ids.first_entry->name_id.id == 0)
4017 /* Fall through so that NEXT is dropped. */
4019 else if (entry->value.directory->names.num_entries == 0
4020 && entry->value.directory->ids.num_entries == 1
4021 && !entry->value.directory->ids.first_entry->is_name
4022 && entry->value.directory->ids.first_entry->name_id.id == 0)
4024 /* Swap ENTRY and NEXT. Then fall through so that the old ENTRY is dropped. */
4025 entry->next_entry = next->next_entry;
4026 next->next_entry = entry;
4027 * points_to_entry = next;
4028 points_to_entry = & next->next_entry;
4029 next = entry->next_entry;
4030 swapped = true;
4032 else
4034 _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
4035 bfd_set_error (bfd_error_file_truncated);
4036 return;
4039 /* Unhook NEXT from the chain. */
4040 /* FIXME: memory loss here. */
4041 entry->next_entry = next->next_entry;
4042 chain->num_entries --;
4043 if (chain->num_entries < 2)
4044 return;
4045 next = next->next_entry;
4047 else
4048 rsrc_merge (entry, next);
4050 else if (entry->is_dir != next->is_dir)
4052 _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
4053 bfd_set_error (bfd_error_file_truncated);
4054 return;
4056 else
4058 /* Otherwise with identical leaves we issue an error
4059 message - because there should never be duplicates.
4060 The exception is Type 18/Name 1/Lang 0 which is the
4061 defaul manifest - this can just be dropped. */
4062 if (!entry->is_name
4063 && entry->name_id.id == 0
4064 && dir != NULL
4065 && dir->entry != NULL
4066 && !dir->entry->is_name
4067 && dir->entry->name_id.id == 1
4068 && dir->entry->parent != NULL
4069 && dir->entry->parent->entry != NULL
4070 && !dir->entry->parent->entry->is_name
4071 && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
4073 else if (dir != NULL
4074 && dir->entry != NULL
4075 && dir->entry->parent != NULL
4076 && dir->entry->parent->entry != NULL
4077 && !dir->entry->parent->entry->is_name
4078 && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
4080 /* Strings need special handling. */
4081 if (! rsrc_merge_string_entries (entry, next))
4083 /* _bfd_error_handler should have been called inside merge_strings. */
4084 bfd_set_error (bfd_error_file_truncated);
4085 return;
4088 else
4090 if (dir == NULL
4091 || dir->entry == NULL
4092 || dir->entry->parent == NULL
4093 || dir->entry->parent->entry == NULL)
4094 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
4095 else
4097 char buff[256];
4099 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
4100 rsrc_resource_name (entry, dir, buff));
4102 bfd_set_error (bfd_error_file_truncated);
4103 return;
4107 /* Unhook NEXT from the chain. */
4108 entry->next_entry = next->next_entry;
4109 chain->num_entries --;
4110 if (chain->num_entries < 2)
4111 return;
4112 next = next->next_entry;
4114 else
4116 points_to_entry = & entry->next_entry;
4117 entry = next;
4118 next = next->next_entry;
4121 while (next);
4123 chain->last_entry = entry;
4125 while (swapped);
4128 /* Attach B's chain onto A. */
4129 static void
4130 rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
4132 if (bchain->num_entries == 0)
4133 return;
4135 achain->num_entries += bchain->num_entries;
4137 if (achain->first_entry == NULL)
4139 achain->first_entry = bchain->first_entry;
4140 achain->last_entry = bchain->last_entry;
4142 else
4144 achain->last_entry->next_entry = bchain->first_entry;
4145 achain->last_entry = bchain->last_entry;
4148 bchain->num_entries = 0;
4149 bchain->first_entry = bchain->last_entry = NULL;
4152 static void
4153 rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
4155 rsrc_directory * adir;
4156 rsrc_directory * bdir;
4158 BFD_ASSERT (a->is_dir);
4159 BFD_ASSERT (b->is_dir);
4161 adir = a->value.directory;
4162 bdir = b->value.directory;
4164 if (adir->characteristics != bdir->characteristics)
4166 _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics"));
4167 bfd_set_error (bfd_error_file_truncated);
4168 return;
4171 if (adir->major != bdir->major || adir->minor != bdir->minor)
4173 _bfd_error_handler (_(".rsrc merge failure: differing directory versions"));
4174 bfd_set_error (bfd_error_file_truncated);
4175 return;
4178 /* Attach B's name chain to A. */
4179 rsrc_attach_chain (& adir->names, & bdir->names);
4181 /* Attach B's ID chain to A. */
4182 rsrc_attach_chain (& adir->ids, & bdir->ids);
4184 /* Now sort A's entries. */
4185 rsrc_sort_entries (& adir->names, true, adir);
4186 rsrc_sort_entries (& adir->ids, false, adir);
4189 /* Check the .rsrc section. If it contains multiple concatenated
4190 resources then we must merge them properly. Otherwise Windows
4191 will ignore all but the first set. */
4193 static void
4194 rsrc_process_section (bfd * abfd,
4195 struct coff_final_link_info * pfinfo)
4197 rsrc_directory new_table;
4198 bfd_size_type size;
4199 asection * sec;
4200 pe_data_type * pe;
4201 bfd_vma rva_bias;
4202 bfd_byte * data;
4203 bfd_byte * datastart;
4204 bfd_byte * dataend;
4205 bfd_byte * new_data;
4206 unsigned int num_resource_sets;
4207 rsrc_directory * type_tables;
4208 rsrc_write_data write_data;
4209 unsigned int indx;
4210 bfd * input;
4211 unsigned int num_input_rsrc = 0;
4212 unsigned int max_num_input_rsrc = 4;
4213 ptrdiff_t * rsrc_sizes = NULL;
4215 new_table.names.num_entries = 0;
4216 new_table.ids.num_entries = 0;
4218 sec = bfd_get_section_by_name (abfd, ".rsrc");
4219 if (sec == NULL || (size = sec->rawsize) == 0)
4220 return;
4222 pe = pe_data (abfd);
4223 if (pe == NULL)
4224 return;
4226 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4228 if (! bfd_malloc_and_get_section (abfd, sec, &datastart))
4229 goto end;
4231 /* Step zero: Scan the input bfds looking for .rsrc sections and record
4232 their lengths. Note - we rely upon the fact that the linker script
4233 does *not* sort the input .rsrc sections, so that the order in the
4234 linkinfo list matches the order in the output .rsrc section.
4236 We need to know the lengths because each input .rsrc section has padding
4237 at the end of a variable amount. (It does not appear to be based upon
4238 the section alignment or the file alignment). We need to skip any
4239 padding bytes when parsing the input .rsrc sections. */
4240 data = datastart;
4241 rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof (*rsrc_sizes));
4242 if (rsrc_sizes == NULL)
4243 goto end;
4245 for (input = pfinfo->info->input_bfds;
4246 input != NULL;
4247 input = input->link.next)
4249 asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
4251 /* PR 18372 - skip discarded .rsrc sections. */
4252 if (rsrc_sec != NULL && !discarded_section (rsrc_sec))
4254 if (num_input_rsrc == max_num_input_rsrc)
4256 max_num_input_rsrc += 10;
4257 rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
4258 * sizeof (*rsrc_sizes));
4259 if (rsrc_sizes == NULL)
4260 goto end;
4263 BFD_ASSERT (rsrc_sec->size > 0);
4264 rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
4268 if (num_input_rsrc < 2)
4269 goto end;
4271 /* Step one: Walk the section, computing the size of the tables,
4272 leaves and data and decide if we need to do anything. */
4273 dataend = data + size;
4274 num_resource_sets = 0;
4276 while (data < dataend)
4278 bfd_byte * p = data;
4280 data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
4282 if (data > dataend)
4284 /* Corrupted .rsrc section - cannot merge. */
4285 _bfd_error_handler (_("%pB: .rsrc merge failure: corrupt .rsrc section"),
4286 abfd);
4287 bfd_set_error (bfd_error_file_truncated);
4288 goto end;
4291 if ((data - p) > rsrc_sizes [num_resource_sets])
4293 _bfd_error_handler (_("%pB: .rsrc merge failure: unexpected .rsrc size"),
4294 abfd);
4295 bfd_set_error (bfd_error_file_truncated);
4296 goto end;
4298 /* FIXME: Should we add a check for "data - p" being much smaller
4299 than rsrc_sizes[num_resource_sets] ? */
4301 data = p + rsrc_sizes[num_resource_sets];
4302 rva_bias += data - p;
4303 ++ num_resource_sets;
4305 BFD_ASSERT (num_resource_sets == num_input_rsrc);
4307 /* Step two: Walk the data again, building trees of the resources. */
4308 data = datastart;
4309 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4311 type_tables = bfd_malloc (num_resource_sets * sizeof (*type_tables));
4312 if (type_tables == NULL)
4313 goto end;
4315 indx = 0;
4316 while (data < dataend)
4318 bfd_byte * p = data;
4320 (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
4321 dataend, rva_bias, NULL);
4322 data = p + rsrc_sizes[indx];
4323 rva_bias += data - p;
4324 ++ indx;
4326 BFD_ASSERT (indx == num_resource_sets);
4328 /* Step three: Merge the top level tables (there can be only one).
4330 We must ensure that the merged entries are in ascending order.
4332 We also thread the top level table entries from the old tree onto
4333 the new table, so that they can be pulled off later. */
4335 /* FIXME: Should we verify that all type tables are the same ? */
4336 new_table.characteristics = type_tables[0].characteristics;
4337 new_table.time = type_tables[0].time;
4338 new_table.major = type_tables[0].major;
4339 new_table.minor = type_tables[0].minor;
4341 /* Chain the NAME entries onto the table. */
4342 new_table.names.first_entry = NULL;
4343 new_table.names.last_entry = NULL;
4345 for (indx = 0; indx < num_resource_sets; indx++)
4346 rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
4348 rsrc_sort_entries (& new_table.names, true, & new_table);
4350 /* Chain the ID entries onto the table. */
4351 new_table.ids.first_entry = NULL;
4352 new_table.ids.last_entry = NULL;
4354 for (indx = 0; indx < num_resource_sets; indx++)
4355 rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
4357 rsrc_sort_entries (& new_table.ids, false, & new_table);
4359 /* Step four: Create new contents for the .rsrc section. */
4360 /* Step four point one: Compute the size of each region of the .rsrc section.
4361 We do this now, rather than earlier, as the merging above may have dropped
4362 some entries. */
4363 sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
4364 rsrc_compute_region_sizes (& new_table);
4365 /* We increment sizeof_strings to make sure that resource data
4366 starts on an 8-byte boundary. FIXME: Is this correct ? */
4367 sizeof_strings = (sizeof_strings + 7) & ~ 7;
4369 new_data = bfd_zalloc (abfd, size);
4370 if (new_data == NULL)
4371 goto end;
4373 write_data.abfd = abfd;
4374 write_data.datastart = new_data;
4375 write_data.next_table = new_data;
4376 write_data.next_leaf = new_data + sizeof_tables_and_entries;
4377 write_data.next_string = write_data.next_leaf + sizeof_leaves;
4378 write_data.next_data = write_data.next_string + sizeof_strings;
4379 write_data.rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4381 rsrc_write_directory (& write_data, & new_table);
4383 /* Step five: Replace the old contents with the new.
4384 We don't recompute the size as it's too late here to shrink section.
4385 See PR ld/20193 for more details. */
4386 bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
4387 sec->size = sec->rawsize = size;
4389 end:
4390 /* Step six: Free all the memory that we have used. */
4391 /* FIXME: Free the resource tree, if we have one. */
4392 free (datastart);
4393 free (rsrc_sizes);
4396 /* Handle the .idata section and other things that need symbol table
4397 access. */
4399 bool
4400 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
4402 struct coff_link_hash_entry *h1;
4403 struct bfd_link_info *info = pfinfo->info;
4404 bool result = true;
4406 /* There are a few fields that need to be filled in now while we
4407 have symbol table access.
4409 The .idata subsections aren't directly available as sections, but
4410 they are in the symbol table, so get them from there. */
4412 /* The import directory. This is the address of .idata$2, with size
4413 of .idata$2 + .idata$3. */
4414 h1 = coff_link_hash_lookup (coff_hash_table (info),
4415 ".idata$2", false, false, true);
4416 if (h1 != NULL)
4418 /* PR ld/2729: We cannot rely upon all the output sections having been
4419 created properly, so check before referencing them. Issue a warning
4420 message for any sections tht could not be found. */
4421 if ((h1->root.type == bfd_link_hash_defined
4422 || h1->root.type == bfd_link_hash_defweak)
4423 && h1->root.u.def.section != NULL
4424 && h1->root.u.def.section->output_section != NULL)
4425 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
4426 (h1->root.u.def.value
4427 + h1->root.u.def.section->output_section->vma
4428 + h1->root.u.def.section->output_offset);
4429 else
4431 _bfd_error_handler
4432 (_("%pB: unable to fill in DataDictionary[1] because .idata$2 is missing"),
4433 abfd);
4434 result = false;
4437 h1 = coff_link_hash_lookup (coff_hash_table (info),
4438 ".idata$4", false, false, true);
4439 if (h1 != NULL
4440 && (h1->root.type == bfd_link_hash_defined
4441 || h1->root.type == bfd_link_hash_defweak)
4442 && h1->root.u.def.section != NULL
4443 && h1->root.u.def.section->output_section != NULL)
4444 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
4445 ((h1->root.u.def.value
4446 + h1->root.u.def.section->output_section->vma
4447 + h1->root.u.def.section->output_offset)
4448 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
4449 else
4451 _bfd_error_handler
4452 (_("%pB: unable to fill in DataDictionary[1] because .idata$4 is missing"),
4453 abfd);
4454 result = false;
4457 /* The import address table. This is the size/address of
4458 .idata$5. */
4459 h1 = coff_link_hash_lookup (coff_hash_table (info),
4460 ".idata$5", false, false, true);
4461 if (h1 != NULL
4462 && (h1->root.type == bfd_link_hash_defined
4463 || h1->root.type == bfd_link_hash_defweak)
4464 && h1->root.u.def.section != NULL
4465 && h1->root.u.def.section->output_section != NULL)
4466 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4467 (h1->root.u.def.value
4468 + h1->root.u.def.section->output_section->vma
4469 + h1->root.u.def.section->output_offset);
4470 else
4472 _bfd_error_handler
4473 (_("%pB: unable to fill in DataDictionary[12] because .idata$5 is missing"),
4474 abfd);
4475 result = false;
4478 h1 = coff_link_hash_lookup (coff_hash_table (info),
4479 ".idata$6", false, false, true);
4480 if (h1 != NULL
4481 && (h1->root.type == bfd_link_hash_defined
4482 || h1->root.type == bfd_link_hash_defweak)
4483 && h1->root.u.def.section != NULL
4484 && h1->root.u.def.section->output_section != NULL)
4485 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4486 ((h1->root.u.def.value
4487 + h1->root.u.def.section->output_section->vma
4488 + h1->root.u.def.section->output_offset)
4489 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
4490 else
4492 _bfd_error_handler
4493 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
4494 abfd);
4495 result = false;
4498 else
4500 h1 = coff_link_hash_lookup (coff_hash_table (info),
4501 "__IAT_start__", false, false, true);
4502 if (h1 != NULL
4503 && (h1->root.type == bfd_link_hash_defined
4504 || h1->root.type == bfd_link_hash_defweak)
4505 && h1->root.u.def.section != NULL
4506 && h1->root.u.def.section->output_section != NULL)
4508 bfd_vma iat_va;
4510 iat_va =
4511 (h1->root.u.def.value
4512 + h1->root.u.def.section->output_section->vma
4513 + h1->root.u.def.section->output_offset);
4515 h1 = coff_link_hash_lookup (coff_hash_table (info),
4516 "__IAT_end__", false, false, true);
4517 if (h1 != NULL
4518 && (h1->root.type == bfd_link_hash_defined
4519 || h1->root.type == bfd_link_hash_defweak)
4520 && h1->root.u.def.section != NULL
4521 && h1->root.u.def.section->output_section != NULL)
4523 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4524 ((h1->root.u.def.value
4525 + h1->root.u.def.section->output_section->vma
4526 + h1->root.u.def.section->output_offset)
4527 - iat_va);
4528 if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
4529 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4530 iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
4532 else
4534 _bfd_error_handler
4535 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
4536 " because .idata$6 is missing"), abfd);
4537 result = false;
4542 h1 = coff_link_hash_lookup (coff_hash_table (info),
4543 (bfd_get_symbol_leading_char (abfd) != 0
4544 ? "__tls_used" : "_tls_used"),
4545 false, false, true);
4546 if (h1 != NULL)
4548 if ((h1->root.type == bfd_link_hash_defined
4549 || h1->root.type == bfd_link_hash_defweak)
4550 && h1->root.u.def.section != NULL
4551 && h1->root.u.def.section->output_section != NULL)
4552 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
4553 (h1->root.u.def.value
4554 + h1->root.u.def.section->output_section->vma
4555 + h1->root.u.def.section->output_offset
4556 - pe_data (abfd)->pe_opthdr.ImageBase);
4557 else
4559 _bfd_error_handler
4560 (_("%pB: unable to fill in DataDictionary[9] because __tls_used is missing"),
4561 abfd);
4562 result = false;
4564 /* According to PECOFF sepcifications by Microsoft version 8.2
4565 the TLS data directory consists of 4 pointers, followed
4566 by two 4-byte integer. This implies that the total size
4567 is different for 32-bit and 64-bit executables. */
4568 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
4569 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
4570 #else
4571 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
4572 #endif
4575 /* If there is a .pdata section and we have linked pdata finally, we
4576 need to sort the entries ascending. */
4577 #if !defined(COFF_WITH_pep) && (defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64))
4579 asection *sec = bfd_get_section_by_name (abfd, ".pdata");
4581 if (sec)
4583 bfd_size_type x = sec->rawsize;
4584 bfd_byte *tmp_data;
4586 if (bfd_malloc_and_get_section (abfd, sec, &tmp_data))
4588 qsort (tmp_data,
4589 (size_t) (x / 12),
4590 12, sort_x64_pdata);
4591 bfd_set_section_contents (pfinfo->output_bfd, sec,
4592 tmp_data, 0, x);
4593 free (tmp_data);
4595 else
4596 result = false;
4599 #endif
4601 rsrc_process_section (abfd, pfinfo);
4603 /* If we couldn't find idata$2, we either have an excessively
4604 trivial program or are in DEEP trouble; we have to assume trivial
4605 program.... */
4606 return result;