Document the GDB 10.2 release in gdb/ChangeLog
[binutils-gdb.git] / bfd / peXXigen.c
blobc41c3299277846875ee7eca9ca00e530b2683d61
1 /* Support for the generic parts of PE/PEI; the common executable parts.
2 Copyright (C) 1995-2021 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, or COFF_WITH_pex64
64 depending on whether we're compiling for straight PE or PE+. */
65 #define COFF_WITH_XX
67 #include "sysdep.h"
68 #include "bfd.h"
69 #include "libbfd.h"
70 #include "coff/internal.h"
71 #include "bfdver.h"
72 #include "libiberty.h"
73 #include <wchar.h>
74 #include <wctype.h>
76 /* NOTE: it's strange to be including an architecture specific header
77 in what's supposed to be general (to PE/PEI) code. However, that's
78 where the definitions are, and they don't vary per architecture
79 within PE/PEI, so we get them from there. FIXME: The lack of
80 variance is an assumption which may prove to be incorrect if new
81 PE/PEI targets are created. */
82 #if defined COFF_WITH_pex64
83 # include "coff/x86_64.h"
84 #elif defined COFF_WITH_pep
85 # include "coff/ia64.h"
86 #else
87 # include "coff/i386.h"
88 #endif
90 #include "coff/pe.h"
91 #include "libcoff.h"
92 #include "libpei.h"
93 #include "safe-ctype.h"
95 #if defined COFF_WITH_pep || defined COFF_WITH_pex64
96 # undef AOUTSZ
97 # define AOUTSZ PEPAOUTSZ
98 # define PEAOUTHDR PEPAOUTHDR
99 #endif
101 #define HighBitSet(val) ((val) & 0x80000000)
102 #define SetHighBit(val) ((val) | 0x80000000)
103 #define WithoutHighBit(val) ((val) & 0x7fffffff)
105 void
106 _bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1)
108 SYMENT *ext = (SYMENT *) ext1;
109 struct internal_syment *in = (struct internal_syment *) in1;
111 if (ext->e.e_name[0] == 0)
113 in->_n._n_n._n_zeroes = 0;
114 in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
116 else
117 memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
119 in->n_value = H_GET_32 (abfd, ext->e_value);
120 in->n_scnum = (short) H_GET_16 (abfd, ext->e_scnum);
122 if (sizeof (ext->e_type) == 2)
123 in->n_type = H_GET_16 (abfd, ext->e_type);
124 else
125 in->n_type = H_GET_32 (abfd, ext->e_type);
127 in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
128 in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
130 #ifndef STRICT_PE_FORMAT
131 /* This is for Gnu-created DLLs. */
133 /* The section symbols for the .idata$ sections have class 0x68
134 (C_SECTION), which MS documentation indicates is a section
135 symbol. Unfortunately, the value field in the symbol is simply a
136 copy of the .idata section's flags rather than something useful.
137 When these symbols are encountered, change the value to 0 so that
138 they will be handled somewhat correctly in the bfd code. */
139 if (in->n_sclass == C_SECTION)
141 char namebuf[SYMNMLEN + 1];
142 const char *name = NULL;
144 in->n_value = 0x0;
146 /* Create synthetic empty sections as needed. DJ */
147 if (in->n_scnum == 0)
149 asection *sec;
151 name = _bfd_coff_internal_syment_name (abfd, in, namebuf);
152 if (name == NULL)
154 _bfd_error_handler (_("%pB: unable to find name for empty section"),
155 abfd);
156 bfd_set_error (bfd_error_invalid_target);
157 return;
160 sec = bfd_get_section_by_name (abfd, name);
161 if (sec != NULL)
162 in->n_scnum = sec->target_index;
165 if (in->n_scnum == 0)
167 int unused_section_number = 0;
168 asection *sec;
169 flagword flags;
170 size_t name_len;
171 char *sec_name;
173 for (sec = abfd->sections; sec; sec = sec->next)
174 if (unused_section_number <= sec->target_index)
175 unused_section_number = sec->target_index + 1;
177 name_len = strlen (name) + 1;
178 sec_name = bfd_alloc (abfd, name_len);
179 if (sec_name == NULL)
181 _bfd_error_handler (_("%pB: out of memory creating name "
182 "for empty section"), abfd);
183 return;
185 memcpy (sec_name, name, name_len);
187 flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD;
188 sec = bfd_make_section_anyway_with_flags (abfd, sec_name, flags);
189 if (sec == NULL)
191 _bfd_error_handler (_("%pB: unable to create fake empty section"),
192 abfd);
193 return;
196 sec->vma = 0;
197 sec->lma = 0;
198 sec->size = 0;
199 sec->filepos = 0;
200 sec->rel_filepos = 0;
201 sec->reloc_count = 0;
202 sec->line_filepos = 0;
203 sec->lineno_count = 0;
204 sec->userdata = NULL;
205 sec->next = NULL;
206 sec->alignment_power = 2;
208 sec->target_index = unused_section_number;
210 in->n_scnum = unused_section_number;
212 in->n_sclass = C_STAT;
214 #endif
217 static bool
218 abs_finder (bfd * abfd ATTRIBUTE_UNUSED, asection * sec, void * data)
220 bfd_vma abs_val = * (bfd_vma *) data;
222 return (sec->vma <= abs_val) && ((sec->vma + (1ULL << 32)) > abs_val);
225 unsigned int
226 _bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp)
228 struct internal_syment *in = (struct internal_syment *) inp;
229 SYMENT *ext = (SYMENT *) extp;
231 if (in->_n._n_name[0] == 0)
233 H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
234 H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
236 else
237 memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
239 /* The PE32 and PE32+ formats only use 4 bytes to hold the value of a
240 symbol. This is a problem on 64-bit targets where we can generate
241 absolute symbols with values >= 1^32. We try to work around this
242 problem by finding a section whose base address is sufficient to
243 reduce the absolute value to < 1^32, and then transforming the
244 symbol into a section relative symbol. This of course is a hack. */
245 if (sizeof (in->n_value) > 4
246 /* The strange computation of the shift amount is here in order to
247 avoid a compile time warning about the comparison always being
248 false. It does not matter if this test fails to work as expected
249 as the worst that can happen is that some absolute symbols are
250 needlessly converted into section relative symbols. */
251 && in->n_value > ((1ULL << (sizeof (in->n_value) > 4 ? 32 : 31)) - 1)
252 && in->n_scnum == N_ABS)
254 asection * sec;
256 sec = bfd_sections_find_if (abfd, abs_finder, & in->n_value);
257 if (sec)
259 in->n_value -= sec->vma;
260 in->n_scnum = sec->target_index;
262 /* else: FIXME: The value is outside the range of any section. This
263 happens for __image_base__ and __ImageBase and maybe some other
264 symbols as well. We should find a way to handle these values. */
267 H_PUT_32 (abfd, in->n_value, ext->e_value);
268 H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
270 if (sizeof (ext->e_type) == 2)
271 H_PUT_16 (abfd, in->n_type, ext->e_type);
272 else
273 H_PUT_32 (abfd, in->n_type, ext->e_type);
275 H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
276 H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
278 return SYMESZ;
281 void
282 _bfd_XXi_swap_aux_in (bfd * abfd,
283 void * ext1,
284 int type,
285 int in_class,
286 int indx ATTRIBUTE_UNUSED,
287 int numaux ATTRIBUTE_UNUSED,
288 void * in1)
290 AUXENT *ext = (AUXENT *) ext1;
291 union internal_auxent *in = (union internal_auxent *) in1;
293 /* PR 17521: Make sure that all fields in the aux structure
294 are initialised. */
295 memset (in, 0, sizeof * in);
296 switch (in_class)
298 case C_FILE:
299 if (ext->x_file.x_fname[0] == 0)
301 in->x_file.x_n.x_zeroes = 0;
302 in->x_file.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset);
304 else
305 memcpy (in->x_file.x_fname, ext->x_file.x_fname, FILNMLEN);
306 return;
308 case C_STAT:
309 case C_LEAFSTAT:
310 case C_HIDDEN:
311 if (type == T_NULL)
313 in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext);
314 in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext);
315 in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext);
316 in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum);
317 in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated);
318 in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat);
319 return;
321 break;
324 in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->x_sym.x_tagndx);
325 in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx);
327 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
328 || ISTAG (in_class))
330 in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext);
331 in->x_sym.x_fcnary.x_fcn.x_endndx.l = GET_FCN_ENDNDX (abfd, ext);
333 else
335 in->x_sym.x_fcnary.x_ary.x_dimen[0] =
336 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
337 in->x_sym.x_fcnary.x_ary.x_dimen[1] =
338 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
339 in->x_sym.x_fcnary.x_ary.x_dimen[2] =
340 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
341 in->x_sym.x_fcnary.x_ary.x_dimen[3] =
342 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
345 if (ISFCN (type))
347 in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
349 else
351 in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext);
352 in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext);
356 unsigned int
357 _bfd_XXi_swap_aux_out (bfd * abfd,
358 void * inp,
359 int type,
360 int in_class,
361 int indx ATTRIBUTE_UNUSED,
362 int numaux ATTRIBUTE_UNUSED,
363 void * extp)
365 union internal_auxent *in = (union internal_auxent *) inp;
366 AUXENT *ext = (AUXENT *) extp;
368 memset (ext, 0, AUXESZ);
370 switch (in_class)
372 case C_FILE:
373 if (in->x_file.x_fname[0] == 0)
375 H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes);
376 H_PUT_32 (abfd, in->x_file.x_n.x_offset, ext->x_file.x_n.x_offset);
378 else
379 memcpy (ext->x_file.x_fname, in->x_file.x_fname, sizeof (ext->x_file.x_fname));
381 return AUXESZ;
383 case C_STAT:
384 case C_LEAFSTAT:
385 case C_HIDDEN:
386 if (type == T_NULL)
388 PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext);
389 PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext);
390 PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext);
391 H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum);
392 H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated);
393 H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat);
394 return AUXESZ;
396 break;
399 H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->x_sym.x_tagndx);
400 H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx);
402 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
403 || ISTAG (in_class))
405 PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr, ext);
406 PUT_FCN_ENDNDX (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.l, ext);
408 else
410 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0],
411 ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
412 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1],
413 ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
414 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2],
415 ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
416 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3],
417 ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
420 if (ISFCN (type))
421 H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize);
422 else
424 PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext);
425 PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext);
428 return AUXESZ;
431 void
432 _bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
434 LINENO *ext = (LINENO *) ext1;
435 struct internal_lineno *in = (struct internal_lineno *) in1;
437 in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
438 in->l_lnno = GET_LINENO_LNNO (abfd, ext);
441 unsigned int
442 _bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp)
444 struct internal_lineno *in = (struct internal_lineno *) inp;
445 struct external_lineno *ext = (struct external_lineno *) outp;
446 H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx);
448 PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
449 return LINESZ;
452 void
453 _bfd_XXi_swap_aouthdr_in (bfd * abfd,
454 void * aouthdr_ext1,
455 void * aouthdr_int1)
457 PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1;
458 AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1;
459 struct internal_aouthdr *aouthdr_int
460 = (struct internal_aouthdr *) aouthdr_int1;
461 struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe;
463 aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic);
464 aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp);
465 aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize);
466 aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize);
467 aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize);
468 aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry);
469 aouthdr_int->text_start =
470 GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start);
472 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
473 /* PE32+ does not have data_start member! */
474 aouthdr_int->data_start =
475 GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start);
476 a->BaseOfData = aouthdr_int->data_start;
477 #endif
479 a->Magic = aouthdr_int->magic;
480 a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp);
481 a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1);
482 a->SizeOfCode = aouthdr_int->tsize ;
483 a->SizeOfInitializedData = aouthdr_int->dsize ;
484 a->SizeOfUninitializedData = aouthdr_int->bsize ;
485 a->AddressOfEntryPoint = aouthdr_int->entry;
486 a->BaseOfCode = aouthdr_int->text_start;
487 a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase);
488 a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment);
489 a->FileAlignment = H_GET_32 (abfd, src->FileAlignment);
490 a->MajorOperatingSystemVersion =
491 H_GET_16 (abfd, src->MajorOperatingSystemVersion);
492 a->MinorOperatingSystemVersion =
493 H_GET_16 (abfd, src->MinorOperatingSystemVersion);
494 a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion);
495 a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion);
496 a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion);
497 a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion);
498 a->Reserved1 = H_GET_32 (abfd, src->Reserved1);
499 a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage);
500 a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders);
501 a->CheckSum = H_GET_32 (abfd, src->CheckSum);
502 a->Subsystem = H_GET_16 (abfd, src->Subsystem);
503 a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics);
504 a->SizeOfStackReserve =
505 GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve);
506 a->SizeOfStackCommit =
507 GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit);
508 a->SizeOfHeapReserve =
509 GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve);
510 a->SizeOfHeapCommit =
511 GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit);
512 a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags);
513 a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes);
516 unsigned idx;
518 /* PR 17512: Corrupt PE binaries can cause seg-faults. */
519 if (a->NumberOfRvaAndSizes > IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
521 /* xgettext:c-format */
522 _bfd_error_handler
523 (_("%pB: aout header specifies an invalid number of"
524 " data-directory entries: %u"), abfd, a->NumberOfRvaAndSizes);
525 bfd_set_error (bfd_error_bad_value);
527 /* Paranoia: If the number is corrupt, then assume that the
528 actual entries themselves might be corrupt as well. */
529 a->NumberOfRvaAndSizes = 0;
532 for (idx = 0; idx < a->NumberOfRvaAndSizes; idx++)
534 /* If data directory is empty, rva also should be 0. */
535 int size =
536 H_GET_32 (abfd, src->DataDirectory[idx][1]);
538 a->DataDirectory[idx].Size = size;
540 if (size)
541 a->DataDirectory[idx].VirtualAddress =
542 H_GET_32 (abfd, src->DataDirectory[idx][0]);
543 else
544 a->DataDirectory[idx].VirtualAddress = 0;
547 while (idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
549 a->DataDirectory[idx].Size = 0;
550 a->DataDirectory[idx].VirtualAddress = 0;
551 idx ++;
555 if (aouthdr_int->entry)
557 aouthdr_int->entry += a->ImageBase;
558 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
559 aouthdr_int->entry &= 0xffffffff;
560 #endif
563 if (aouthdr_int->tsize)
565 aouthdr_int->text_start += a->ImageBase;
566 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
567 aouthdr_int->text_start &= 0xffffffff;
568 #endif
571 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
572 /* PE32+ does not have data_start member! */
573 if (aouthdr_int->dsize)
575 aouthdr_int->data_start += a->ImageBase;
576 aouthdr_int->data_start &= 0xffffffff;
578 #endif
581 /* A support function for below. */
583 static void
584 add_data_entry (bfd * abfd,
585 struct internal_extra_pe_aouthdr *aout,
586 int idx,
587 char *name,
588 bfd_vma base)
590 asection *sec = bfd_get_section_by_name (abfd, name);
592 /* Add import directory information if it exists. */
593 if ((sec != NULL)
594 && (coff_section_data (abfd, sec) != NULL)
595 && (pei_section_data (abfd, sec) != NULL))
597 /* If data directory is empty, rva also should be 0. */
598 int size = pei_section_data (abfd, sec)->virt_size;
599 aout->DataDirectory[idx].Size = size;
601 if (size)
603 aout->DataDirectory[idx].VirtualAddress =
604 (sec->vma - base) & 0xffffffff;
605 sec->flags |= SEC_DATA;
610 unsigned int
611 _bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out)
613 struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in;
614 pe_data_type *pe = pe_data (abfd);
615 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
616 PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out;
617 bfd_vma sa, fa, ib;
618 IMAGE_DATA_DIRECTORY idata2, idata5, tls;
620 sa = extra->SectionAlignment;
621 fa = extra->FileAlignment;
622 ib = extra->ImageBase;
624 idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE];
625 idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE];
626 tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE];
628 if (aouthdr_in->tsize)
630 aouthdr_in->text_start -= ib;
631 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
632 aouthdr_in->text_start &= 0xffffffff;
633 #endif
636 if (aouthdr_in->dsize)
638 aouthdr_in->data_start -= ib;
639 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
640 aouthdr_in->data_start &= 0xffffffff;
641 #endif
644 if (aouthdr_in->entry)
646 aouthdr_in->entry -= ib;
647 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
648 aouthdr_in->entry &= 0xffffffff;
649 #endif
652 #define FA(x) (((x) + fa -1 ) & (- fa))
653 #define SA(x) (((x) + sa -1 ) & (- sa))
655 /* We like to have the sizes aligned. */
656 aouthdr_in->bsize = FA (aouthdr_in->bsize);
658 extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
660 add_data_entry (abfd, extra, PE_EXPORT_TABLE, ".edata", ib);
661 add_data_entry (abfd, extra, PE_RESOURCE_TABLE, ".rsrc", ib);
662 add_data_entry (abfd, extra, PE_EXCEPTION_TABLE, ".pdata", ib);
664 /* In theory we do not need to call add_data_entry for .idata$2 or
665 .idata$5. It will be done in bfd_coff_final_link where all the
666 required information is available. If however, we are not going
667 to perform a final link, eg because we have been invoked by objcopy
668 or strip, then we need to make sure that these Data Directory
669 entries are initialised properly.
671 So - we copy the input values into the output values, and then, if
672 a final link is going to be performed, it can overwrite them. */
673 extra->DataDirectory[PE_IMPORT_TABLE] = idata2;
674 extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5;
675 extra->DataDirectory[PE_TLS_TABLE] = tls;
677 if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0)
678 /* Until other .idata fixes are made (pending patch), the entry for
679 .idata is needed for backwards compatibility. FIXME. */
680 add_data_entry (abfd, extra, PE_IMPORT_TABLE, ".idata", ib);
682 /* For some reason, the virtual size (which is what's set by
683 add_data_entry) for .reloc is not the same as the size recorded
684 in this slot by MSVC; it doesn't seem to cause problems (so far),
685 but since it's the best we've got, use it. It does do the right
686 thing for .pdata. */
687 if (pe->has_reloc_section)
688 add_data_entry (abfd, extra, PE_BASE_RELOCATION_TABLE, ".reloc", ib);
691 asection *sec;
692 bfd_vma hsize = 0;
693 bfd_vma dsize = 0;
694 bfd_vma isize = 0;
695 bfd_vma tsize = 0;
697 for (sec = abfd->sections; sec; sec = sec->next)
699 int rounded = FA (sec->size);
701 if (rounded == 0)
702 continue;
704 /* The first non-zero section filepos is the header size.
705 Sections without contents will have a filepos of 0. */
706 if (hsize == 0)
707 hsize = sec->filepos;
708 if (sec->flags & SEC_DATA)
709 dsize += rounded;
710 if (sec->flags & SEC_CODE)
711 tsize += rounded;
712 /* The image size is the total VIRTUAL size (which is what is
713 in the virt_size field). Files have been seen (from MSVC
714 5.0 link.exe) where the file size of the .data segment is
715 quite small compared to the virtual size. Without this
716 fix, strip munges the file.
718 FIXME: We need to handle holes between sections, which may
719 happpen when we covert from another format. We just use
720 the virtual address and virtual size of the last section
721 for the image size. */
722 if (coff_section_data (abfd, sec) != NULL
723 && pei_section_data (abfd, sec) != NULL)
724 isize = (sec->vma - extra->ImageBase
725 + SA (FA (pei_section_data (abfd, sec)->virt_size)));
728 aouthdr_in->dsize = dsize;
729 aouthdr_in->tsize = tsize;
730 extra->SizeOfHeaders = hsize;
731 extra->SizeOfImage = isize;
734 H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
736 /* e.g. 219510000 is linker version 2.19 */
737 #define LINKER_VERSION ((short) (BFD_VERSION / 1000000))
739 /* This piece of magic sets the "linker version" field to
740 LINKER_VERSION. */
741 H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256),
742 aouthdr_out->standard.vstamp);
744 PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize);
745 PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize);
746 PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize);
747 PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry);
748 PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start,
749 aouthdr_out->standard.text_start);
751 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
752 /* PE32+ does not have data_start member! */
753 PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start,
754 aouthdr_out->standard.data_start);
755 #endif
757 PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase);
758 H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment);
759 H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment);
760 H_PUT_16 (abfd, extra->MajorOperatingSystemVersion,
761 aouthdr_out->MajorOperatingSystemVersion);
762 H_PUT_16 (abfd, extra->MinorOperatingSystemVersion,
763 aouthdr_out->MinorOperatingSystemVersion);
764 H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion);
765 H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion);
766 H_PUT_16 (abfd, extra->MajorSubsystemVersion,
767 aouthdr_out->MajorSubsystemVersion);
768 H_PUT_16 (abfd, extra->MinorSubsystemVersion,
769 aouthdr_out->MinorSubsystemVersion);
770 H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1);
771 H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage);
772 H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders);
773 H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum);
774 H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem);
775 H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics);
776 PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve,
777 aouthdr_out->SizeOfStackReserve);
778 PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit,
779 aouthdr_out->SizeOfStackCommit);
780 PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve,
781 aouthdr_out->SizeOfHeapReserve);
782 PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit,
783 aouthdr_out->SizeOfHeapCommit);
784 H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags);
785 H_PUT_32 (abfd, extra->NumberOfRvaAndSizes,
786 aouthdr_out->NumberOfRvaAndSizes);
788 int idx;
790 for (idx = 0; idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; idx++)
792 H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress,
793 aouthdr_out->DataDirectory[idx][0]);
794 H_PUT_32 (abfd, extra->DataDirectory[idx].Size,
795 aouthdr_out->DataDirectory[idx][1]);
799 return AOUTSZ;
802 unsigned int
803 _bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
805 int idx;
806 struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
807 struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out;
809 if (pe_data (abfd)->has_reloc_section
810 || pe_data (abfd)->dont_strip_reloc)
811 filehdr_in->f_flags &= ~F_RELFLG;
813 if (pe_data (abfd)->dll)
814 filehdr_in->f_flags |= F_DLL;
816 filehdr_in->pe.e_magic = IMAGE_DOS_SIGNATURE;
817 filehdr_in->pe.e_cblp = 0x90;
818 filehdr_in->pe.e_cp = 0x3;
819 filehdr_in->pe.e_crlc = 0x0;
820 filehdr_in->pe.e_cparhdr = 0x4;
821 filehdr_in->pe.e_minalloc = 0x0;
822 filehdr_in->pe.e_maxalloc = 0xffff;
823 filehdr_in->pe.e_ss = 0x0;
824 filehdr_in->pe.e_sp = 0xb8;
825 filehdr_in->pe.e_csum = 0x0;
826 filehdr_in->pe.e_ip = 0x0;
827 filehdr_in->pe.e_cs = 0x0;
828 filehdr_in->pe.e_lfarlc = 0x40;
829 filehdr_in->pe.e_ovno = 0x0;
831 for (idx = 0; idx < 4; idx++)
832 filehdr_in->pe.e_res[idx] = 0x0;
834 filehdr_in->pe.e_oemid = 0x0;
835 filehdr_in->pe.e_oeminfo = 0x0;
837 for (idx = 0; idx < 10; idx++)
838 filehdr_in->pe.e_res2[idx] = 0x0;
840 filehdr_in->pe.e_lfanew = 0x80;
842 /* This next collection of data are mostly just characters. It
843 appears to be constant within the headers put on NT exes. */
844 memcpy (filehdr_in->pe.dos_message, pe_data (abfd)->dos_message,
845 sizeof (filehdr_in->pe.dos_message));
847 filehdr_in->pe.nt_signature = IMAGE_NT_SIGNATURE;
849 H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
850 H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
852 /* Use a real timestamp by default, unless the no-insert-timestamp
853 option was chosen. */
854 if ((pe_data (abfd)->timestamp) == -1)
855 H_PUT_32 (abfd, time (0), filehdr_out->f_timdat);
856 else
857 H_PUT_32 (abfd, pe_data (abfd)->timestamp, filehdr_out->f_timdat);
859 PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr,
860 filehdr_out->f_symptr);
861 H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
862 H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
863 H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
865 /* Put in extra dos header stuff. This data remains essentially
866 constant, it just has to be tacked on to the beginning of all exes
867 for NT. */
868 H_PUT_16 (abfd, filehdr_in->pe.e_magic, filehdr_out->e_magic);
869 H_PUT_16 (abfd, filehdr_in->pe.e_cblp, filehdr_out->e_cblp);
870 H_PUT_16 (abfd, filehdr_in->pe.e_cp, filehdr_out->e_cp);
871 H_PUT_16 (abfd, filehdr_in->pe.e_crlc, filehdr_out->e_crlc);
872 H_PUT_16 (abfd, filehdr_in->pe.e_cparhdr, filehdr_out->e_cparhdr);
873 H_PUT_16 (abfd, filehdr_in->pe.e_minalloc, filehdr_out->e_minalloc);
874 H_PUT_16 (abfd, filehdr_in->pe.e_maxalloc, filehdr_out->e_maxalloc);
875 H_PUT_16 (abfd, filehdr_in->pe.e_ss, filehdr_out->e_ss);
876 H_PUT_16 (abfd, filehdr_in->pe.e_sp, filehdr_out->e_sp);
877 H_PUT_16 (abfd, filehdr_in->pe.e_csum, filehdr_out->e_csum);
878 H_PUT_16 (abfd, filehdr_in->pe.e_ip, filehdr_out->e_ip);
879 H_PUT_16 (abfd, filehdr_in->pe.e_cs, filehdr_out->e_cs);
880 H_PUT_16 (abfd, filehdr_in->pe.e_lfarlc, filehdr_out->e_lfarlc);
881 H_PUT_16 (abfd, filehdr_in->pe.e_ovno, filehdr_out->e_ovno);
883 for (idx = 0; idx < 4; idx++)
884 H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]);
886 H_PUT_16 (abfd, filehdr_in->pe.e_oemid, filehdr_out->e_oemid);
887 H_PUT_16 (abfd, filehdr_in->pe.e_oeminfo, filehdr_out->e_oeminfo);
889 for (idx = 0; idx < 10; idx++)
890 H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]);
892 H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew);
894 for (idx = 0; idx < 16; idx++)
895 H_PUT_32 (abfd, filehdr_in->pe.dos_message[idx],
896 filehdr_out->dos_message[idx]);
898 /* Also put in the NT signature. */
899 H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature);
901 return FILHSZ;
904 unsigned int
905 _bfd_XX_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
907 struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
908 FILHDR *filehdr_out = (FILHDR *) out;
910 H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
911 H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
912 H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->f_timdat);
913 PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr);
914 H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
915 H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
916 H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
918 return FILHSZ;
921 unsigned int
922 _bfd_XXi_swap_scnhdr_out (bfd * abfd, void * in, void * out)
924 struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in;
925 SCNHDR *scnhdr_ext = (SCNHDR *) out;
926 unsigned int ret = SCNHSZ;
927 bfd_vma ps;
928 bfd_vma ss;
930 memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name));
932 ss = scnhdr_int->s_vaddr - pe_data (abfd)->pe_opthdr.ImageBase;
933 if (scnhdr_int->s_vaddr < pe_data (abfd)->pe_opthdr.ImageBase)
934 _bfd_error_handler (_("%pB:%.8s: section below image base"),
935 abfd, scnhdr_int->s_name);
936 else if(ss != (ss & 0xffffffff))
937 _bfd_error_handler (_("%pB:%.8s: RVA truncated"), abfd, scnhdr_int->s_name);
938 PUT_SCNHDR_VADDR (abfd, ss & 0xffffffff, scnhdr_ext->s_vaddr);
940 /* NT wants the size data to be rounded up to the next
941 NT_FILE_ALIGNMENT, but zero if it has no content (as in .bss,
942 sometimes). */
943 if ((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
945 if (bfd_pei_p (abfd))
947 ps = scnhdr_int->s_size;
948 ss = 0;
950 else
952 ps = 0;
953 ss = scnhdr_int->s_size;
956 else
958 if (bfd_pei_p (abfd))
959 ps = scnhdr_int->s_paddr;
960 else
961 ps = 0;
963 ss = scnhdr_int->s_size;
966 PUT_SCNHDR_SIZE (abfd, ss,
967 scnhdr_ext->s_size);
969 /* s_paddr in PE is really the virtual size. */
970 PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr);
972 PUT_SCNHDR_SCNPTR (abfd, scnhdr_int->s_scnptr,
973 scnhdr_ext->s_scnptr);
974 PUT_SCNHDR_RELPTR (abfd, scnhdr_int->s_relptr,
975 scnhdr_ext->s_relptr);
976 PUT_SCNHDR_LNNOPTR (abfd, scnhdr_int->s_lnnoptr,
977 scnhdr_ext->s_lnnoptr);
980 /* Extra flags must be set when dealing with PE. All sections should also
981 have the IMAGE_SCN_MEM_READ (0x40000000) flag set. In addition, the
982 .text section must have IMAGE_SCN_MEM_EXECUTE (0x20000000) and the data
983 sections (.idata, .data, .bss, .CRT) must have IMAGE_SCN_MEM_WRITE set
984 (this is especially important when dealing with the .idata section since
985 the addresses for routines from .dlls must be overwritten). If .reloc
986 section data is ever generated, we must add IMAGE_SCN_MEM_DISCARDABLE
987 (0x02000000). Also, the resource data should also be read and
988 writable. */
990 /* FIXME: Alignment is also encoded in this field, at least on
991 ARM-WINCE. Although - how do we get the original alignment field
992 back ? */
994 typedef struct
996 char section_name[SCNNMLEN];
997 unsigned long must_have;
999 pe_required_section_flags;
1001 pe_required_section_flags known_sections [] =
1003 { ".arch", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
1004 { ".bss", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1005 { ".data", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1006 { ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1007 { ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1008 { ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1009 { ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1010 { ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
1011 { ".rsrc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1012 { ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
1013 { ".tls", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1014 { ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1017 pe_required_section_flags * p;
1019 /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
1020 we know exactly what this specific section wants so we remove it
1021 and then allow the must_have field to add it back in if necessary.
1022 However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
1023 default WP_TEXT file flag has been cleared. WP_TEXT may be cleared
1024 by ld --enable-auto-import (if auto-import is actually needed),
1025 by ld --omagic, or by obcopy --writable-text. */
1027 for (p = known_sections;
1028 p < known_sections + ARRAY_SIZE (known_sections);
1029 p++)
1030 if (memcmp (scnhdr_int->s_name, p->section_name, SCNNMLEN) == 0)
1032 if (memcmp (scnhdr_int->s_name, ".text", sizeof ".text")
1033 || (bfd_get_file_flags (abfd) & WP_TEXT))
1034 scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
1035 scnhdr_int->s_flags |= p->must_have;
1036 break;
1039 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1042 if (coff_data (abfd)->link_info
1043 && ! bfd_link_relocatable (coff_data (abfd)->link_info)
1044 && ! bfd_link_pic (coff_data (abfd)->link_info)
1045 && memcmp (scnhdr_int->s_name, ".text", sizeof ".text") == 0)
1047 /* By inference from looking at MS output, the 32 bit field
1048 which is the combination of the number_of_relocs and
1049 number_of_linenos is used for the line number count in
1050 executables. A 16-bit field won't do for cc1. The MS
1051 document says that the number of relocs is zero for
1052 executables, but the 17-th bit has been observed to be there.
1053 Overflow is not an issue: a 4G-line program will overflow a
1054 bunch of other fields long before this! */
1055 H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
1056 H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
1058 else
1060 if (scnhdr_int->s_nlnno <= 0xffff)
1061 H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
1062 else
1064 /* xgettext:c-format */
1065 _bfd_error_handler (_("%pB: line number overflow: 0x%lx > 0xffff"),
1066 abfd, scnhdr_int->s_nlnno);
1067 bfd_set_error (bfd_error_file_truncated);
1068 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
1069 ret = 0;
1072 /* Although we could encode 0xffff relocs here, we do not, to be
1073 consistent with other parts of bfd. Also it lets us warn, as
1074 we should never see 0xffff here w/o having the overflow flag
1075 set. */
1076 if (scnhdr_int->s_nreloc < 0xffff)
1077 H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
1078 else
1080 /* PE can deal with large #s of relocs, but not here. */
1081 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
1082 scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
1083 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1086 return ret;
1089 void
1090 _bfd_XXi_swap_debugdir_in (bfd * abfd, void * ext1, void * in1)
1092 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1;
1093 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1;
1095 in->Characteristics = H_GET_32(abfd, ext->Characteristics);
1096 in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp);
1097 in->MajorVersion = H_GET_16(abfd, ext->MajorVersion);
1098 in->MinorVersion = H_GET_16(abfd, ext->MinorVersion);
1099 in->Type = H_GET_32(abfd, ext->Type);
1100 in->SizeOfData = H_GET_32(abfd, ext->SizeOfData);
1101 in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData);
1102 in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData);
1105 unsigned int
1106 _bfd_XXi_swap_debugdir_out (bfd * abfd, void * inp, void * extp)
1108 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp;
1109 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp;
1111 H_PUT_32(abfd, in->Characteristics, ext->Characteristics);
1112 H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp);
1113 H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion);
1114 H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion);
1115 H_PUT_32(abfd, in->Type, ext->Type);
1116 H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData);
1117 H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData);
1118 H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData);
1120 return sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1123 CODEVIEW_INFO *
1124 _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo)
1126 char buffer[256+1];
1127 bfd_size_type nread;
1129 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1130 return NULL;
1132 if (length <= sizeof (CV_INFO_PDB70) && length <= sizeof (CV_INFO_PDB20))
1133 return NULL;
1134 if (length > 256)
1135 length = 256;
1136 nread = bfd_bread (buffer, length, abfd);
1137 if (length != nread)
1138 return NULL;
1140 /* Ensure null termination of filename. */
1141 memset (buffer + nread, 0, sizeof (buffer) - nread);
1143 cvinfo->CVSignature = H_GET_32 (abfd, buffer);
1144 cvinfo->Age = 0;
1146 if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
1147 && (length > sizeof (CV_INFO_PDB70)))
1149 CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
1151 cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
1153 /* A GUID consists of 4,2,2 byte values in little-endian order, followed
1154 by 8 single bytes. Byte swap them so we can conveniently treat the GUID
1155 as 16 bytes in big-endian order. */
1156 bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
1157 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
1158 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
1159 memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
1161 cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
1162 /* cvinfo->PdbFileName = cvinfo70->PdbFileName; */
1164 return cvinfo;
1166 else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
1167 && (length > sizeof (CV_INFO_PDB20)))
1169 CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
1170 cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
1171 memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
1172 cvinfo->SignatureLength = 4;
1173 /* cvinfo->PdbFileName = cvinfo20->PdbFileName; */
1175 return cvinfo;
1178 return NULL;
1181 unsigned int
1182 _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo)
1184 const bfd_size_type size = sizeof (CV_INFO_PDB70) + 1;
1185 bfd_size_type written;
1186 CV_INFO_PDB70 *cvinfo70;
1187 char * buffer;
1189 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1190 return 0;
1192 buffer = bfd_malloc (size);
1193 if (buffer == NULL)
1194 return 0;
1196 cvinfo70 = (CV_INFO_PDB70 *) buffer;
1197 H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
1199 /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
1200 in little-endian order, followed by 8 single bytes. */
1201 bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
1202 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
1203 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
1204 memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
1206 H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
1207 cvinfo70->PdbFileName[0] = '\0';
1209 written = bfd_bwrite (buffer, size, abfd);
1211 free (buffer);
1213 return written == size ? size : 0;
1216 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
1218 N_("Export Directory [.edata (or where ever we found it)]"),
1219 N_("Import Directory [parts of .idata]"),
1220 N_("Resource Directory [.rsrc]"),
1221 N_("Exception Directory [.pdata]"),
1222 N_("Security Directory"),
1223 N_("Base Relocation Directory [.reloc]"),
1224 N_("Debug Directory"),
1225 N_("Description Directory"),
1226 N_("Special Directory"),
1227 N_("Thread Storage Directory [.tls]"),
1228 N_("Load Configuration Directory"),
1229 N_("Bound Import Directory"),
1230 N_("Import Address Table Directory"),
1231 N_("Delay Import Directory"),
1232 N_("CLR Runtime Header"),
1233 N_("Reserved")
1236 static bool
1237 pe_print_idata (bfd * abfd, void * vfile)
1239 FILE *file = (FILE *) vfile;
1240 bfd_byte *data;
1241 asection *section;
1242 bfd_signed_vma adj;
1243 bfd_size_type datasize = 0;
1244 bfd_size_type dataoff;
1245 bfd_size_type i;
1246 int onaline = 20;
1248 pe_data_type *pe = pe_data (abfd);
1249 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1251 bfd_vma addr;
1253 addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
1255 if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
1257 /* Maybe the extra header isn't there. Look for the section. */
1258 section = bfd_get_section_by_name (abfd, ".idata");
1259 if (section == NULL)
1260 return true;
1262 addr = section->vma;
1263 datasize = section->size;
1264 if (datasize == 0)
1265 return true;
1267 else
1269 addr += extra->ImageBase;
1270 for (section = abfd->sections; section != NULL; section = section->next)
1272 datasize = section->size;
1273 if (addr >= section->vma && addr < section->vma + datasize)
1274 break;
1277 if (section == NULL)
1279 fprintf (file,
1280 _("\nThere is an import table, but the section containing it could not be found\n"));
1281 return true;
1283 else if (!(section->flags & SEC_HAS_CONTENTS))
1285 fprintf (file,
1286 _("\nThere is an import table in %s, but that section has no contents\n"),
1287 section->name);
1288 return true;
1292 /* xgettext:c-format */
1293 fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
1294 section->name, (unsigned long) addr);
1296 dataoff = addr - section->vma;
1298 fprintf (file,
1299 _("\nThe Import Tables (interpreted %s section contents)\n"),
1300 section->name);
1301 fprintf (file,
1302 _("\
1303 vma: Hint Time Forward DLL First\n\
1304 Table Stamp Chain Name Thunk\n"));
1306 /* Read the whole section. Some of the fields might be before dataoff. */
1307 if (!bfd_malloc_and_get_section (abfd, section, &data))
1309 free (data);
1310 return false;
1313 adj = section->vma - extra->ImageBase;
1315 /* Print all image import descriptors. */
1316 for (i = dataoff; i + onaline <= datasize; i += onaline)
1318 bfd_vma hint_addr;
1319 bfd_vma time_stamp;
1320 bfd_vma forward_chain;
1321 bfd_vma dll_name;
1322 bfd_vma first_thunk;
1323 int idx = 0;
1324 bfd_size_type j;
1325 char *dll;
1327 /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress). */
1328 fprintf (file, " %08lx\t", (unsigned long) (i + adj));
1329 hint_addr = bfd_get_32 (abfd, data + i);
1330 time_stamp = bfd_get_32 (abfd, data + i + 4);
1331 forward_chain = bfd_get_32 (abfd, data + i + 8);
1332 dll_name = bfd_get_32 (abfd, data + i + 12);
1333 first_thunk = bfd_get_32 (abfd, data + i + 16);
1335 fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
1336 (unsigned long) hint_addr,
1337 (unsigned long) time_stamp,
1338 (unsigned long) forward_chain,
1339 (unsigned long) dll_name,
1340 (unsigned long) first_thunk);
1342 if (hint_addr == 0 && first_thunk == 0)
1343 break;
1345 if (dll_name - adj >= section->size)
1346 break;
1348 dll = (char *) data + dll_name - adj;
1349 /* PR 17512 file: 078-12277-0.004. */
1350 bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
1351 fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
1353 /* PR 21546: When the Hint Address is zero,
1354 we try the First Thunk instead. */
1355 if (hint_addr == 0)
1356 hint_addr = first_thunk;
1358 if (hint_addr != 0 && hint_addr - adj < datasize)
1360 bfd_byte *ft_data;
1361 asection *ft_section;
1362 bfd_vma ft_addr;
1363 bfd_size_type ft_datasize;
1364 int ft_idx;
1365 int ft_allocated;
1367 fprintf (file, _("\tvma: Hint/Ord Member-Name Bound-To\n"));
1369 idx = hint_addr - adj;
1371 ft_addr = first_thunk + extra->ImageBase;
1372 ft_idx = first_thunk - adj;
1373 ft_data = data + ft_idx;
1374 ft_datasize = datasize - ft_idx;
1375 ft_allocated = 0;
1377 if (first_thunk != hint_addr)
1379 /* Find the section which contains the first thunk. */
1380 for (ft_section = abfd->sections;
1381 ft_section != NULL;
1382 ft_section = ft_section->next)
1384 if (ft_addr >= ft_section->vma
1385 && ft_addr < ft_section->vma + ft_section->size)
1386 break;
1389 if (ft_section == NULL)
1391 fprintf (file,
1392 _("\nThere is a first thunk, but the section containing it could not be found\n"));
1393 continue;
1396 /* Now check to see if this section is the same as our current
1397 section. If it is not then we will have to load its data in. */
1398 if (ft_section != section)
1400 ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
1401 ft_datasize = ft_section->size - ft_idx;
1402 ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
1403 if (ft_data == NULL)
1404 continue;
1406 /* Read ft_datasize bytes starting at offset ft_idx. */
1407 if (!bfd_get_section_contents (abfd, ft_section, ft_data,
1408 (bfd_vma) ft_idx, ft_datasize))
1410 free (ft_data);
1411 continue;
1413 ft_allocated = 1;
1417 /* Print HintName vector entries. */
1418 #ifdef COFF_WITH_pex64
1419 for (j = 0; idx + j + 8 <= datasize; j += 8)
1421 bfd_size_type amt;
1422 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1423 unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
1425 if (!member && !member_high)
1426 break;
1428 amt = member - adj;
1430 if (HighBitSet (member_high))
1431 fprintf (file, "\t%lx%08lx\t %4lx%08lx <none>",
1432 member_high, member,
1433 WithoutHighBit (member_high), member);
1434 /* PR binutils/17512: Handle corrupt PE data. */
1435 else if (amt >= datasize || amt + 2 >= datasize)
1436 fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
1437 else
1439 int ordinal;
1440 char *member_name;
1442 ordinal = bfd_get_16 (abfd, data + amt);
1443 member_name = (char *) data + amt + 2;
1444 fprintf (file, "\t%04lx\t %4d %.*s",member, ordinal,
1445 (int) (datasize - (amt + 2)), member_name);
1448 /* If the time stamp is not zero, the import address
1449 table holds actual addresses. */
1450 if (time_stamp != 0
1451 && first_thunk != 0
1452 && first_thunk != hint_addr
1453 && j + 4 <= ft_datasize)
1454 fprintf (file, "\t%04lx",
1455 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1456 fprintf (file, "\n");
1458 #else
1459 for (j = 0; idx + j + 4 <= datasize; j += 4)
1461 bfd_size_type amt;
1462 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1464 /* Print single IMAGE_IMPORT_BY_NAME vector. */
1465 if (member == 0)
1466 break;
1468 amt = member - adj;
1470 if (HighBitSet (member))
1471 fprintf (file, "\t%04lx\t %4lu <none>",
1472 member, WithoutHighBit (member));
1473 /* PR binutils/17512: Handle corrupt PE data. */
1474 else if (amt >= datasize || amt + 2 >= datasize)
1475 fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
1476 else
1478 int ordinal;
1479 char *member_name;
1481 ordinal = bfd_get_16 (abfd, data + amt);
1482 member_name = (char *) data + amt + 2;
1483 fprintf (file, "\t%04lx\t %4d %.*s",
1484 member, ordinal,
1485 (int) (datasize - (amt + 2)), member_name);
1488 /* If the time stamp is not zero, the import address
1489 table holds actual addresses. */
1490 if (time_stamp != 0
1491 && first_thunk != 0
1492 && first_thunk != hint_addr
1493 && j + 4 <= ft_datasize)
1494 fprintf (file, "\t%04lx",
1495 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1497 fprintf (file, "\n");
1499 #endif
1500 if (ft_allocated)
1501 free (ft_data);
1504 fprintf (file, "\n");
1507 free (data);
1509 return true;
1512 static bool
1513 pe_print_edata (bfd * abfd, void * vfile)
1515 FILE *file = (FILE *) vfile;
1516 bfd_byte *data;
1517 asection *section;
1518 bfd_size_type datasize = 0;
1519 bfd_size_type dataoff;
1520 bfd_size_type i;
1521 bfd_vma adj;
1522 struct EDT_type
1524 long export_flags; /* Reserved - should be zero. */
1525 long time_stamp;
1526 short major_ver;
1527 short minor_ver;
1528 bfd_vma name; /* RVA - relative to image base. */
1529 long base; /* Ordinal base. */
1530 unsigned long num_functions;/* Number in the export address table. */
1531 unsigned long num_names; /* Number in the name pointer table. */
1532 bfd_vma eat_addr; /* RVA to the export address table. */
1533 bfd_vma npt_addr; /* RVA to the Export Name Pointer Table. */
1534 bfd_vma ot_addr; /* RVA to the Ordinal Table. */
1535 } edt;
1537 pe_data_type *pe = pe_data (abfd);
1538 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1540 bfd_vma addr;
1542 addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
1544 if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
1546 /* Maybe the extra header isn't there. Look for the section. */
1547 section = bfd_get_section_by_name (abfd, ".edata");
1548 if (section == NULL)
1549 return true;
1551 addr = section->vma;
1552 dataoff = 0;
1553 datasize = section->size;
1554 if (datasize == 0)
1555 return true;
1557 else
1559 addr += extra->ImageBase;
1561 for (section = abfd->sections; section != NULL; section = section->next)
1562 if (addr >= section->vma && addr < section->vma + section->size)
1563 break;
1565 if (section == NULL)
1567 fprintf (file,
1568 _("\nThere is an export table, but the section containing it could not be found\n"));
1569 return true;
1571 else if (!(section->flags & SEC_HAS_CONTENTS))
1573 fprintf (file,
1574 _("\nThere is an export table in %s, but that section has no contents\n"),
1575 section->name);
1576 return true;
1579 dataoff = addr - section->vma;
1580 datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
1581 if (dataoff > section->size
1582 || datasize > section->size - dataoff)
1584 fprintf (file,
1585 _("\nThere is an export table in %s, but it does not fit into that section\n"),
1586 section->name);
1587 return true;
1591 /* PR 17512: Handle corrupt PE binaries. */
1592 if (datasize < 40)
1594 fprintf (file,
1595 /* xgettext:c-format */
1596 _("\nThere is an export table in %s, but it is too small (%d)\n"),
1597 section->name, (int) datasize);
1598 return true;
1601 /* xgettext:c-format */
1602 fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
1603 section->name, (unsigned long) addr);
1605 data = (bfd_byte *) bfd_malloc (datasize);
1606 if (data == NULL)
1607 return false;
1609 if (! bfd_get_section_contents (abfd, section, data,
1610 (file_ptr) dataoff, datasize))
1611 return false;
1613 /* Go get Export Directory Table. */
1614 edt.export_flags = bfd_get_32 (abfd, data + 0);
1615 edt.time_stamp = bfd_get_32 (abfd, data + 4);
1616 edt.major_ver = bfd_get_16 (abfd, data + 8);
1617 edt.minor_ver = bfd_get_16 (abfd, data + 10);
1618 edt.name = bfd_get_32 (abfd, data + 12);
1619 edt.base = bfd_get_32 (abfd, data + 16);
1620 edt.num_functions = bfd_get_32 (abfd, data + 20);
1621 edt.num_names = bfd_get_32 (abfd, data + 24);
1622 edt.eat_addr = bfd_get_32 (abfd, data + 28);
1623 edt.npt_addr = bfd_get_32 (abfd, data + 32);
1624 edt.ot_addr = bfd_get_32 (abfd, data + 36);
1626 adj = section->vma - extra->ImageBase + dataoff;
1628 /* Dump the EDT first. */
1629 fprintf (file,
1630 _("\nThe Export Tables (interpreted %s section contents)\n\n"),
1631 section->name);
1633 fprintf (file,
1634 _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
1636 fprintf (file,
1637 _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
1639 fprintf (file,
1640 /* xgettext:c-format */
1641 _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
1643 fprintf (file,
1644 _("Name \t\t\t\t"));
1645 bfd_fprintf_vma (abfd, file, edt.name);
1647 if ((edt.name >= adj) && (edt.name < adj + datasize))
1648 fprintf (file, " %.*s\n",
1649 (int) (datasize - (edt.name - adj)),
1650 data + edt.name - adj);
1651 else
1652 fprintf (file, "(outside .edata section)\n");
1654 fprintf (file,
1655 _("Ordinal Base \t\t\t%ld\n"), edt.base);
1657 fprintf (file,
1658 _("Number in:\n"));
1660 fprintf (file,
1661 _("\tExport Address Table \t\t%08lx\n"),
1662 edt.num_functions);
1664 fprintf (file,
1665 _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
1667 fprintf (file,
1668 _("Table Addresses\n"));
1670 fprintf (file,
1671 _("\tExport Address Table \t\t"));
1672 bfd_fprintf_vma (abfd, file, edt.eat_addr);
1673 fprintf (file, "\n");
1675 fprintf (file,
1676 _("\tName Pointer Table \t\t"));
1677 bfd_fprintf_vma (abfd, file, edt.npt_addr);
1678 fprintf (file, "\n");
1680 fprintf (file,
1681 _("\tOrdinal Table \t\t\t"));
1682 bfd_fprintf_vma (abfd, file, edt.ot_addr);
1683 fprintf (file, "\n");
1685 /* The next table to find is the Export Address Table. It's basically
1686 a list of pointers that either locate a function in this dll, or
1687 forward the call to another dll. Something like:
1688 typedef union
1690 long export_rva;
1691 long forwarder_rva;
1692 } export_address_table_entry; */
1694 fprintf (file,
1695 _("\nExport Address Table -- Ordinal Base %ld\n"),
1696 edt.base);
1698 /* PR 17512: Handle corrupt PE binaries. */
1699 /* PR 17512 file: 140-165018-0.004. */
1700 if (edt.eat_addr - adj >= datasize
1701 /* PR 17512: file: 092b1829 */
1702 || (edt.num_functions + 1) * 4 < edt.num_functions
1703 || edt.eat_addr - adj + (edt.num_functions + 1) * 4 > datasize)
1704 fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
1705 (long) edt.eat_addr,
1706 (long) edt.num_functions);
1707 else for (i = 0; i < edt.num_functions; ++i)
1709 bfd_vma eat_member = bfd_get_32 (abfd,
1710 data + edt.eat_addr + (i * 4) - adj);
1711 if (eat_member == 0)
1712 continue;
1714 if (eat_member - adj <= datasize)
1716 /* This rva is to a name (forwarding function) in our section. */
1717 /* Should locate a function descriptor. */
1718 fprintf (file,
1719 "\t[%4ld] +base[%4ld] %04lx %s -- %.*s\n",
1720 (long) i,
1721 (long) (i + edt.base),
1722 (unsigned long) eat_member,
1723 _("Forwarder RVA"),
1724 (int)(datasize - (eat_member - adj)),
1725 data + eat_member - adj);
1727 else
1729 /* Should locate a function descriptor in the reldata section. */
1730 fprintf (file,
1731 "\t[%4ld] +base[%4ld] %04lx %s\n",
1732 (long) i,
1733 (long) (i + edt.base),
1734 (unsigned long) eat_member,
1735 _("Export RVA"));
1739 /* The Export Name Pointer Table is paired with the Export Ordinal Table. */
1740 /* Dump them in parallel for clarity. */
1741 fprintf (file,
1742 _("\n[Ordinal/Name Pointer] Table\n"));
1744 /* PR 17512: Handle corrupt PE binaries. */
1745 if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
1746 /* PR 17512: file: bb68816e. */
1747 || edt.num_names * 4 < edt.num_names
1748 || (data + edt.npt_addr - adj) < data)
1749 /* xgettext:c-format */
1750 fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
1751 (long) edt.npt_addr,
1752 (long) edt.num_names);
1753 /* PR 17512: file: 140-147171-0.004. */
1754 else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
1755 || data + edt.ot_addr - adj < data)
1756 /* xgettext:c-format */
1757 fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
1758 (long) edt.ot_addr,
1759 (long) edt.num_names);
1760 else for (i = 0; i < edt.num_names; ++i)
1762 bfd_vma name_ptr;
1763 bfd_vma ord;
1765 ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
1766 name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
1768 if ((name_ptr - adj) >= datasize)
1770 /* xgettext:c-format */
1771 fprintf (file, _("\t[%4ld] <corrupt offset: %lx>\n"),
1772 (long) ord, (long) name_ptr);
1774 else
1776 char * name = (char *) data + name_ptr - adj;
1778 fprintf (file, "\t[%4ld] %.*s\n", (long) ord,
1779 (int)((char *)(data + datasize) - name), name);
1783 free (data);
1785 return true;
1788 /* This really is architecture dependent. On IA-64, a .pdata entry
1789 consists of three dwords containing relative virtual addresses that
1790 specify the start and end address of the code range the entry
1791 covers and the address of the corresponding unwind info data.
1793 On ARM and SH-4, a compressed PDATA structure is used :
1794 _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
1795 _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
1796 See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
1798 This is the version for uncompressed data. */
1800 static bool
1801 pe_print_pdata (bfd * abfd, void * vfile)
1803 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1804 # define PDATA_ROW_SIZE (3 * 8)
1805 #else
1806 # define PDATA_ROW_SIZE (5 * 4)
1807 #endif
1808 FILE *file = (FILE *) vfile;
1809 bfd_byte *data = 0;
1810 asection *section = bfd_get_section_by_name (abfd, ".pdata");
1811 bfd_size_type datasize = 0;
1812 bfd_size_type i;
1813 bfd_size_type start, stop;
1814 int onaline = PDATA_ROW_SIZE;
1816 if (section == NULL
1817 || coff_section_data (abfd, section) == NULL
1818 || pei_section_data (abfd, section) == NULL)
1819 return true;
1821 stop = pei_section_data (abfd, section)->virt_size;
1822 if ((stop % onaline) != 0)
1823 fprintf (file,
1824 /* xgettext:c-format */
1825 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
1826 (long) stop, onaline);
1828 fprintf (file,
1829 _("\nThe Function Table (interpreted .pdata section contents)\n"));
1830 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1831 fprintf (file,
1832 _(" vma:\t\t\tBegin Address End Address Unwind Info\n"));
1833 #else
1834 fprintf (file, _("\
1835 vma:\t\tBegin End EH EH PrologEnd Exception\n\
1836 \t\tAddress Address Handler Data Address Mask\n"));
1837 #endif
1839 datasize = section->size;
1840 if (datasize == 0)
1841 return true;
1843 /* PR 17512: file: 002-193900-0.004. */
1844 if (datasize < stop)
1846 /* xgettext:c-format */
1847 fprintf (file, _("Virtual size of .pdata section (%ld) larger than real size (%ld)\n"),
1848 (long) stop, (long) datasize);
1849 return false;
1852 if (! bfd_malloc_and_get_section (abfd, section, &data))
1854 free (data);
1855 return false;
1858 start = 0;
1860 for (i = start; i < stop; i += onaline)
1862 bfd_vma begin_addr;
1863 bfd_vma end_addr;
1864 bfd_vma eh_handler;
1865 bfd_vma eh_data;
1866 bfd_vma prolog_end_addr;
1867 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1868 int em_data;
1869 #endif
1871 if (i + PDATA_ROW_SIZE > stop)
1872 break;
1874 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
1875 end_addr = GET_PDATA_ENTRY (abfd, data + i + 4);
1876 eh_handler = GET_PDATA_ENTRY (abfd, data + i + 8);
1877 eh_data = GET_PDATA_ENTRY (abfd, data + i + 12);
1878 prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
1880 if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
1881 && eh_data == 0 && prolog_end_addr == 0)
1882 /* We are probably into the padding of the section now. */
1883 break;
1885 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1886 em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
1887 #endif
1888 eh_handler &= ~(bfd_vma) 0x3;
1889 prolog_end_addr &= ~(bfd_vma) 0x3;
1891 fputc (' ', file);
1892 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
1893 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
1894 bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
1895 bfd_fprintf_vma (abfd, file, eh_handler);
1896 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1897 fputc (' ', file);
1898 bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
1899 bfd_fprintf_vma (abfd, file, prolog_end_addr);
1900 fprintf (file, " %x", em_data);
1901 #endif
1902 fprintf (file, "\n");
1905 free (data);
1907 return true;
1908 #undef PDATA_ROW_SIZE
1911 typedef struct sym_cache
1913 int symcount;
1914 asymbol ** syms;
1915 } sym_cache;
1917 static asymbol **
1918 slurp_symtab (bfd *abfd, sym_cache *psc)
1920 asymbol ** sy = NULL;
1921 long storage;
1923 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
1925 psc->symcount = 0;
1926 return NULL;
1929 storage = bfd_get_symtab_upper_bound (abfd);
1930 if (storage < 0)
1931 return NULL;
1932 if (storage)
1934 sy = (asymbol **) bfd_malloc (storage);
1935 if (sy == NULL)
1936 return NULL;
1939 psc->symcount = bfd_canonicalize_symtab (abfd, sy);
1940 if (psc->symcount < 0)
1941 return NULL;
1942 return sy;
1945 static const char *
1946 my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
1948 int i;
1950 if (psc->syms == 0)
1951 psc->syms = slurp_symtab (abfd, psc);
1953 for (i = 0; i < psc->symcount; i++)
1955 if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
1956 return psc->syms[i]->name;
1959 return NULL;
1962 static void
1963 cleanup_syms (sym_cache *psc)
1965 psc->symcount = 0;
1966 free (psc->syms);
1967 psc->syms = NULL;
1970 /* This is the version for "compressed" pdata. */
1972 bool
1973 _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
1975 # define PDATA_ROW_SIZE (2 * 4)
1976 FILE *file = (FILE *) vfile;
1977 bfd_byte *data = NULL;
1978 asection *section = bfd_get_section_by_name (abfd, ".pdata");
1979 bfd_size_type datasize = 0;
1980 bfd_size_type i;
1981 bfd_size_type start, stop;
1982 int onaline = PDATA_ROW_SIZE;
1983 struct sym_cache cache = {0, 0} ;
1985 if (section == NULL
1986 || coff_section_data (abfd, section) == NULL
1987 || pei_section_data (abfd, section) == NULL)
1988 return true;
1990 stop = pei_section_data (abfd, section)->virt_size;
1991 if ((stop % onaline) != 0)
1992 fprintf (file,
1993 /* xgettext:c-format */
1994 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
1995 (long) stop, onaline);
1997 fprintf (file,
1998 _("\nThe Function Table (interpreted .pdata section contents)\n"));
2000 fprintf (file, _("\
2001 vma:\t\tBegin Prolog Function Flags Exception EH\n\
2002 \t\tAddress Length Length 32b exc Handler Data\n"));
2004 datasize = section->size;
2005 if (datasize == 0)
2006 return true;
2008 if (! bfd_malloc_and_get_section (abfd, section, &data))
2010 free (data);
2011 return false;
2014 start = 0;
2016 for (i = start; i < stop; i += onaline)
2018 bfd_vma begin_addr;
2019 bfd_vma other_data;
2020 bfd_vma prolog_length, function_length;
2021 int flag32bit, exception_flag;
2022 asection *tsection;
2024 if (i + PDATA_ROW_SIZE > stop)
2025 break;
2027 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
2028 other_data = GET_PDATA_ENTRY (abfd, data + i + 4);
2030 if (begin_addr == 0 && other_data == 0)
2031 /* We are probably into the padding of the section now. */
2032 break;
2034 prolog_length = (other_data & 0x000000FF);
2035 function_length = (other_data & 0x3FFFFF00) >> 8;
2036 flag32bit = (int)((other_data & 0x40000000) >> 30);
2037 exception_flag = (int)((other_data & 0x80000000) >> 31);
2039 fputc (' ', file);
2040 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
2041 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
2042 bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
2043 bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
2044 fprintf (file, "%2d %2d ", flag32bit, exception_flag);
2046 /* Get the exception handler's address and the data passed from the
2047 .text section. This is really the data that belongs with the .pdata
2048 but got "compressed" out for the ARM and SH4 architectures. */
2049 tsection = bfd_get_section_by_name (abfd, ".text");
2050 if (tsection && coff_section_data (abfd, tsection)
2051 && pei_section_data (abfd, tsection))
2053 bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
2054 bfd_byte *tdata;
2056 tdata = (bfd_byte *) bfd_malloc (8);
2057 if (tdata)
2059 if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
2061 bfd_vma eh, eh_data;
2063 eh = bfd_get_32 (abfd, tdata);
2064 eh_data = bfd_get_32 (abfd, tdata + 4);
2065 fprintf (file, "%08x ", (unsigned int) eh);
2066 fprintf (file, "%08x", (unsigned int) eh_data);
2067 if (eh != 0)
2069 const char *s = my_symbol_for_address (abfd, eh, &cache);
2071 if (s)
2072 fprintf (file, " (%s) ", s);
2075 free (tdata);
2079 fprintf (file, "\n");
2082 free (data);
2084 cleanup_syms (& cache);
2086 return true;
2087 #undef PDATA_ROW_SIZE
2091 #define IMAGE_REL_BASED_HIGHADJ 4
2092 static const char * const tbl[] =
2094 "ABSOLUTE",
2095 "HIGH",
2096 "LOW",
2097 "HIGHLOW",
2098 "HIGHADJ",
2099 "MIPS_JMPADDR",
2100 "SECTION",
2101 "REL32",
2102 "RESERVED1",
2103 "MIPS_JMPADDR16",
2104 "DIR64",
2105 "HIGH3ADJ",
2106 "UNKNOWN", /* MUST be last. */
2109 static bool
2110 pe_print_reloc (bfd * abfd, void * vfile)
2112 FILE *file = (FILE *) vfile;
2113 bfd_byte *data = 0;
2114 asection *section = bfd_get_section_by_name (abfd, ".reloc");
2115 bfd_byte *p, *end;
2117 if (section == NULL || section->size == 0 || !(section->flags & SEC_HAS_CONTENTS))
2118 return true;
2120 fprintf (file,
2121 _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
2123 if (! bfd_malloc_and_get_section (abfd, section, &data))
2125 free (data);
2126 return false;
2129 p = data;
2130 end = data + section->size;
2131 while (p + 8 <= end)
2133 int j;
2134 bfd_vma virtual_address;
2135 unsigned long number, size;
2136 bfd_byte *chunk_end;
2138 /* The .reloc section is a sequence of blocks, with a header consisting
2139 of two 32 bit quantities, followed by a number of 16 bit entries. */
2140 virtual_address = bfd_get_32 (abfd, p);
2141 size = bfd_get_32 (abfd, p + 4);
2142 p += 8;
2143 number = (size - 8) / 2;
2145 if (size == 0)
2146 break;
2148 fprintf (file,
2149 /* xgettext:c-format */
2150 _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
2151 (unsigned long) virtual_address, size, size, number);
2153 chunk_end = p - 8 + size;
2154 if (chunk_end > end)
2155 chunk_end = end;
2156 j = 0;
2157 while (p + 2 <= chunk_end)
2159 unsigned short e = bfd_get_16 (abfd, p);
2160 unsigned int t = (e & 0xF000) >> 12;
2161 int off = e & 0x0FFF;
2163 if (t >= sizeof (tbl) / sizeof (tbl[0]))
2164 t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
2166 fprintf (file,
2167 /* xgettext:c-format */
2168 _("\treloc %4d offset %4x [%4lx] %s"),
2169 j, off, (unsigned long) (off + virtual_address), tbl[t]);
2171 p += 2;
2172 j++;
2174 /* HIGHADJ takes an argument, - the next record *is* the
2175 low 16 bits of addend. */
2176 if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
2178 fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
2179 p += 2;
2180 j++;
2183 fprintf (file, "\n");
2187 free (data);
2189 return true;
2192 /* A data structure describing the regions of a .rsrc section.
2193 Some fields are filled in as the section is parsed. */
2195 typedef struct rsrc_regions
2197 bfd_byte * section_start;
2198 bfd_byte * section_end;
2199 bfd_byte * strings_start;
2200 bfd_byte * resource_start;
2201 } rsrc_regions;
2203 static bfd_byte *
2204 rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
2205 rsrc_regions *, bfd_vma);
2207 /* Print the resource entry at DATA, with the text indented by INDENT.
2208 Recusively calls rsrc_print_resource_directory to print the contents
2209 of directory entries.
2210 Returns the address of the end of the data associated with the entry
2211 or section_end + 1 upon failure. */
2213 static bfd_byte *
2214 rsrc_print_resource_entries (FILE *file,
2215 bfd *abfd,
2216 unsigned int indent,
2217 bool is_name,
2218 bfd_byte *data,
2219 rsrc_regions *regions,
2220 bfd_vma rva_bias)
2222 unsigned long entry, addr, size;
2223 bfd_byte * leaf;
2225 if (data + 8 >= regions->section_end)
2226 return regions->section_end + 1;
2228 /* xgettext:c-format */
2229 fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
2231 entry = (unsigned long) bfd_get_32 (abfd, data);
2232 if (is_name)
2234 bfd_byte * name;
2236 /* Note - the documentation says that this field is an RVA value
2237 but windres appears to produce a section relative offset with
2238 the top bit set. Support both styles for now. */
2239 if (HighBitSet (entry))
2240 name = regions->section_start + WithoutHighBit (entry);
2241 else
2242 name = regions->section_start + entry - rva_bias;
2244 if (name + 2 < regions->section_end && name > regions->section_start)
2246 unsigned int len;
2248 if (regions->strings_start == NULL)
2249 regions->strings_start = name;
2251 len = bfd_get_16 (abfd, name);
2253 fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
2255 if (name + 2 + len * 2 < regions->section_end)
2257 /* This strange loop is to cope with multibyte characters. */
2258 while (len --)
2260 char c;
2262 name += 2;
2263 c = * name;
2264 /* Avoid printing control characters. */
2265 if (c > 0 && c < 32)
2266 fprintf (file, "^%c", c + 64);
2267 else
2268 fprintf (file, "%.1s", name);
2271 else
2273 fprintf (file, _("<corrupt string length: %#x>\n"), len);
2274 /* PR binutils/17512: Do not try to continue decoding a
2275 corrupted resource section. It is likely to end up with
2276 reams of extraneous output. FIXME: We could probably
2277 continue if we disable the printing of strings... */
2278 return regions->section_end + 1;
2281 else
2283 fprintf (file, _("<corrupt string offset: %#lx>\n"), entry);
2284 return regions->section_end + 1;
2287 else
2288 fprintf (file, _("ID: %#08lx"), entry);
2290 entry = (long) bfd_get_32 (abfd, data + 4);
2291 fprintf (file, _(", Value: %#08lx\n"), entry);
2293 if (HighBitSet (entry))
2295 data = regions->section_start + WithoutHighBit (entry);
2296 if (data <= regions->section_start || data > regions->section_end)
2297 return regions->section_end + 1;
2299 /* FIXME: PR binutils/17512: A corrupt file could contain a loop
2300 in the resource table. We need some way to detect this. */
2301 return rsrc_print_resource_directory (file, abfd, indent + 1, data,
2302 regions, rva_bias);
2305 leaf = regions->section_start + entry;
2307 if (leaf + 16 >= regions->section_end
2308 /* PR 17512: file: 055dff7e. */
2309 || leaf < regions->section_start)
2310 return regions->section_end + 1;
2312 /* xgettext:c-format */
2313 fprintf (file, _("%03x %*.s Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
2314 (int) (entry), indent, " ",
2315 addr = (long) bfd_get_32 (abfd, leaf),
2316 size = (long) bfd_get_32 (abfd, leaf + 4),
2317 (int) bfd_get_32 (abfd, leaf + 8));
2319 /* Check that the reserved entry is 0. */
2320 if (bfd_get_32 (abfd, leaf + 12) != 0
2321 /* And that the data address/size is valid too. */
2322 || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
2323 return regions->section_end + 1;
2325 if (regions->resource_start == NULL)
2326 regions->resource_start = regions->section_start + (addr - rva_bias);
2328 return regions->section_start + (addr - rva_bias) + size;
2331 #define max(a,b) ((a) > (b) ? (a) : (b))
2332 #define min(a,b) ((a) < (b) ? (a) : (b))
2334 static bfd_byte *
2335 rsrc_print_resource_directory (FILE * file,
2336 bfd * abfd,
2337 unsigned int indent,
2338 bfd_byte * data,
2339 rsrc_regions * regions,
2340 bfd_vma rva_bias)
2342 unsigned int num_names, num_ids;
2343 bfd_byte * highest_data = data;
2345 if (data + 16 >= regions->section_end)
2346 return regions->section_end + 1;
2348 fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
2349 switch (indent)
2351 case 0: fprintf (file, "Type"); break;
2352 case 2: fprintf (file, "Name"); break;
2353 case 4: fprintf (file, "Language"); break;
2354 default:
2355 fprintf (file, _("<unknown directory type: %d>\n"), indent);
2356 /* FIXME: For now we end the printing here. If in the
2357 future more directory types are added to the RSRC spec
2358 then we will need to change this. */
2359 return regions->section_end + 1;
2362 /* xgettext:c-format */
2363 fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
2364 (int) bfd_get_32 (abfd, data),
2365 (long) bfd_get_32 (abfd, data + 4),
2366 (int) bfd_get_16 (abfd, data + 8),
2367 (int) bfd_get_16 (abfd, data + 10),
2368 num_names = (int) bfd_get_16 (abfd, data + 12),
2369 num_ids = (int) bfd_get_16 (abfd, data + 14));
2370 data += 16;
2372 while (num_names --)
2374 bfd_byte * entry_end;
2376 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, true,
2377 data, regions, rva_bias);
2378 data += 8;
2379 highest_data = max (highest_data, entry_end);
2380 if (entry_end >= regions->section_end)
2381 return entry_end;
2384 while (num_ids --)
2386 bfd_byte * entry_end;
2388 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, false,
2389 data, regions, rva_bias);
2390 data += 8;
2391 highest_data = max (highest_data, entry_end);
2392 if (entry_end >= regions->section_end)
2393 return entry_end;
2396 return max (highest_data, data);
2399 /* Display the contents of a .rsrc section. We do not try to
2400 reproduce the resources, windres does that. Instead we dump
2401 the tables in a human readable format. */
2403 static bool
2404 rsrc_print_section (bfd * abfd, void * vfile)
2406 bfd_vma rva_bias;
2407 pe_data_type * pe;
2408 FILE * file = (FILE *) vfile;
2409 bfd_size_type datasize;
2410 asection * section;
2411 bfd_byte * data;
2412 rsrc_regions regions;
2414 pe = pe_data (abfd);
2415 if (pe == NULL)
2416 return true;
2418 section = bfd_get_section_by_name (abfd, ".rsrc");
2419 if (section == NULL)
2420 return true;
2421 if (!(section->flags & SEC_HAS_CONTENTS))
2422 return true;
2424 datasize = section->size;
2425 if (datasize == 0)
2426 return true;
2428 rva_bias = section->vma - pe->pe_opthdr.ImageBase;
2430 if (! bfd_malloc_and_get_section (abfd, section, & data))
2432 free (data);
2433 return false;
2436 regions.section_start = data;
2437 regions.section_end = data + datasize;
2438 regions.strings_start = NULL;
2439 regions.resource_start = NULL;
2441 fflush (file);
2442 fprintf (file, "\nThe .rsrc Resource Directory section:\n");
2444 while (data < regions.section_end)
2446 bfd_byte * p = data;
2448 data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
2450 if (data == regions.section_end + 1)
2451 fprintf (file, _("Corrupt .rsrc section detected!\n"));
2452 else
2454 /* Align data before continuing. */
2455 int align = (1 << section->alignment_power) - 1;
2457 data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
2458 rva_bias += data - p;
2460 /* For reasons that are unclear .rsrc sections are sometimes created
2461 aligned to a 1^3 boundary even when their alignment is set at
2462 1^2. Catch that case here before we issue a spurious warning
2463 message. */
2464 if (data == (regions.section_end - 4))
2465 data = regions.section_end;
2466 else if (data < regions.section_end)
2468 /* If the extra data is all zeros then do not complain.
2469 This is just padding so that the section meets the
2470 page size requirements. */
2471 while (++ data < regions.section_end)
2472 if (*data != 0)
2473 break;
2474 if (data < regions.section_end)
2475 fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
2480 if (regions.strings_start != NULL)
2481 fprintf (file, _(" String table starts at offset: %#03x\n"),
2482 (int) (regions.strings_start - regions.section_start));
2483 if (regions.resource_start != NULL)
2484 fprintf (file, _(" Resources start at offset: %#03x\n"),
2485 (int) (regions.resource_start - regions.section_start));
2487 free (regions.section_start);
2488 return true;
2491 #define IMAGE_NUMBEROF_DEBUG_TYPES 17
2493 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
2495 "Unknown",
2496 "COFF",
2497 "CodeView",
2498 "FPO",
2499 "Misc",
2500 "Exception",
2501 "Fixup",
2502 "OMAP-to-SRC",
2503 "OMAP-from-SRC",
2504 "Borland",
2505 "Reserved",
2506 "CLSID",
2507 "Feature",
2508 "CoffGrp",
2509 "ILTCG",
2510 "MPX",
2511 "Repro",
2514 static bool
2515 pe_print_debugdata (bfd * abfd, void * vfile)
2517 FILE *file = (FILE *) vfile;
2518 pe_data_type *pe = pe_data (abfd);
2519 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2520 asection *section;
2521 bfd_byte *data = 0;
2522 bfd_size_type dataoff;
2523 unsigned int i, j;
2525 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2526 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2528 if (size == 0)
2529 return true;
2531 addr += extra->ImageBase;
2532 for (section = abfd->sections; section != NULL; section = section->next)
2534 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2535 break;
2538 if (section == NULL)
2540 fprintf (file,
2541 _("\nThere is a debug directory, but the section containing it could not be found\n"));
2542 return true;
2544 else if (!(section->flags & SEC_HAS_CONTENTS))
2546 fprintf (file,
2547 _("\nThere is a debug directory in %s, but that section has no contents\n"),
2548 section->name);
2549 return true;
2551 else if (section->size < size)
2553 fprintf (file,
2554 _("\nError: section %s contains the debug data starting address but it is too small\n"),
2555 section->name);
2556 return false;
2559 fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
2560 section->name, (unsigned long) addr);
2562 dataoff = addr - section->vma;
2564 if (size > (section->size - dataoff))
2566 fprintf (file, _("The debug data size field in the data directory is too big for the section"));
2567 return false;
2570 fprintf (file,
2571 _("Type Size Rva Offset\n"));
2573 /* Read the whole section. */
2574 if (!bfd_malloc_and_get_section (abfd, section, &data))
2576 free (data);
2577 return false;
2580 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2582 const char *type_name;
2583 struct external_IMAGE_DEBUG_DIRECTORY *ext
2584 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2585 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2587 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2589 if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
2590 type_name = debug_type_names[0];
2591 else
2592 type_name = debug_type_names[idd.Type];
2594 fprintf (file, " %2ld %14s %08lx %08lx %08lx\n",
2595 idd.Type, type_name, idd.SizeOfData,
2596 idd.AddressOfRawData, idd.PointerToRawData);
2598 if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
2600 char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
2601 /* PR 17512: file: 065-29434-0.001:0.1
2602 We need to use a 32-bit aligned buffer
2603 to safely read in a codeview record. */
2604 char buffer[256 + 1] ATTRIBUTE_ALIGNED_ALIGNOF (CODEVIEW_INFO);
2606 CODEVIEW_INFO *cvinfo = (CODEVIEW_INFO *) buffer;
2608 /* The debug entry doesn't have to have to be in a section,
2609 in which case AddressOfRawData is 0, so always use PointerToRawData. */
2610 if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
2611 idd.SizeOfData, cvinfo))
2612 continue;
2614 for (j = 0; j < cvinfo->SignatureLength; j++)
2615 sprintf (&signature[j*2], "%02x", cvinfo->Signature[j] & 0xff);
2617 /* xgettext:c-format */
2618 fprintf (file, _("(format %c%c%c%c signature %s age %ld)\n"),
2619 buffer[0], buffer[1], buffer[2], buffer[3],
2620 signature, cvinfo->Age);
2624 free(data);
2626 if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
2627 fprintf (file,
2628 _("The debug directory size is not a multiple of the debug directory entry size\n"));
2630 return true;
2633 static bool
2634 pe_is_repro (bfd * abfd)
2636 pe_data_type *pe = pe_data (abfd);
2637 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2638 asection *section;
2639 bfd_byte *data = 0;
2640 bfd_size_type dataoff;
2641 unsigned int i;
2642 bool res = false;
2644 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2645 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2647 if (size == 0)
2648 return false;
2650 addr += extra->ImageBase;
2651 for (section = abfd->sections; section != NULL; section = section->next)
2653 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2654 break;
2657 if ((section == NULL)
2658 || (!(section->flags & SEC_HAS_CONTENTS))
2659 || (section->size < size))
2661 return false;
2664 dataoff = addr - section->vma;
2666 if (size > (section->size - dataoff))
2668 return false;
2671 if (!bfd_malloc_and_get_section (abfd, section, &data))
2673 free (data);
2674 return false;
2677 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2679 struct external_IMAGE_DEBUG_DIRECTORY *ext
2680 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2681 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2683 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2685 if (idd.Type == PE_IMAGE_DEBUG_TYPE_REPRO)
2687 res = true;
2688 break;
2692 free(data);
2694 return res;
2697 /* Print out the program headers. */
2699 bool
2700 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
2702 FILE *file = (FILE *) vfile;
2703 int j;
2704 pe_data_type *pe = pe_data (abfd);
2705 struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
2706 const char *subsystem_name = NULL;
2707 const char *name;
2709 /* The MS dumpbin program reportedly ands with 0xff0f before
2710 printing the characteristics field. Not sure why. No reason to
2711 emulate it here. */
2712 fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
2713 #undef PF
2714 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
2715 PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
2716 PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
2717 PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
2718 PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
2719 PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
2720 PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
2721 PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
2722 PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
2723 PF (IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "copy to swap file if on removable media");
2724 PF (IMAGE_FILE_NET_RUN_FROM_SWAP, "copy to swap file if on network media");
2725 PF (IMAGE_FILE_SYSTEM, "system file");
2726 PF (IMAGE_FILE_DLL, "DLL");
2727 PF (IMAGE_FILE_UP_SYSTEM_ONLY, "run only on uniprocessor machine");
2728 PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
2729 #undef PF
2732 If a PE_IMAGE_DEBUG_TYPE_REPRO entry is present in the debug directory, the
2733 timestamp is to be interpreted as the hash of a reproducible build.
2735 if (pe_is_repro (abfd))
2737 fprintf (file, "\nTime/Date\t\t%08lx", pe->coff.timestamp);
2738 fprintf (file, "\t(This is a reproducible build file hash, not a timestamp)\n");
2740 else
2742 /* ctime implies '\n'. */
2743 time_t t = pe->coff.timestamp;
2744 fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
2747 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
2748 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
2749 #endif
2750 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
2751 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
2752 #endif
2753 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
2754 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
2755 #endif
2757 switch (i->Magic)
2759 case IMAGE_NT_OPTIONAL_HDR_MAGIC:
2760 name = "PE32";
2761 break;
2762 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
2763 name = "PE32+";
2764 break;
2765 case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
2766 name = "ROM";
2767 break;
2768 default:
2769 name = NULL;
2770 break;
2772 fprintf (file, "Magic\t\t\t%04x", i->Magic);
2773 if (name)
2774 fprintf (file, "\t(%s)",name);
2775 fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
2776 fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
2777 fprintf (file, "SizeOfCode\t\t");
2778 bfd_fprintf_vma (abfd, file, i->SizeOfCode);
2779 fprintf (file, "\nSizeOfInitializedData\t");
2780 bfd_fprintf_vma (abfd, file, i->SizeOfInitializedData);
2781 fprintf (file, "\nSizeOfUninitializedData\t");
2782 bfd_fprintf_vma (abfd, file, i->SizeOfUninitializedData);
2783 fprintf (file, "\nAddressOfEntryPoint\t");
2784 bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
2785 fprintf (file, "\nBaseOfCode\t\t");
2786 bfd_fprintf_vma (abfd, file, i->BaseOfCode);
2787 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
2788 /* PE32+ does not have BaseOfData member! */
2789 fprintf (file, "\nBaseOfData\t\t");
2790 bfd_fprintf_vma (abfd, file, i->BaseOfData);
2791 #endif
2793 fprintf (file, "\nImageBase\t\t");
2794 bfd_fprintf_vma (abfd, file, i->ImageBase);
2795 fprintf (file, "\nSectionAlignment\t%08x\n", i->SectionAlignment);
2796 fprintf (file, "FileAlignment\t\t%08x\n", i->FileAlignment);
2797 fprintf (file, "MajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
2798 fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
2799 fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
2800 fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
2801 fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
2802 fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
2803 fprintf (file, "Win32Version\t\t%08x\n", i->Reserved1);
2804 fprintf (file, "SizeOfImage\t\t%08x\n", i->SizeOfImage);
2805 fprintf (file, "SizeOfHeaders\t\t%08x\n", i->SizeOfHeaders);
2806 fprintf (file, "CheckSum\t\t%08x\n", i->CheckSum);
2808 switch (i->Subsystem)
2810 case IMAGE_SUBSYSTEM_UNKNOWN:
2811 subsystem_name = "unspecified";
2812 break;
2813 case IMAGE_SUBSYSTEM_NATIVE:
2814 subsystem_name = "NT native";
2815 break;
2816 case IMAGE_SUBSYSTEM_WINDOWS_GUI:
2817 subsystem_name = "Windows GUI";
2818 break;
2819 case IMAGE_SUBSYSTEM_WINDOWS_CUI:
2820 subsystem_name = "Windows CUI";
2821 break;
2822 case IMAGE_SUBSYSTEM_POSIX_CUI:
2823 subsystem_name = "POSIX CUI";
2824 break;
2825 case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
2826 subsystem_name = "Wince CUI";
2827 break;
2828 /* These are from UEFI Platform Initialization Specification 1.1. */
2829 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
2830 subsystem_name = "EFI application";
2831 break;
2832 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
2833 subsystem_name = "EFI boot service driver";
2834 break;
2835 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
2836 subsystem_name = "EFI runtime driver";
2837 break;
2838 case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
2839 subsystem_name = "SAL runtime driver";
2840 break;
2841 /* This is from revision 8.0 of the MS PE/COFF spec */
2842 case IMAGE_SUBSYSTEM_XBOX:
2843 subsystem_name = "XBOX";
2844 break;
2845 /* Added default case for clarity - subsystem_name is NULL anyway. */
2846 default:
2847 subsystem_name = NULL;
2850 fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
2851 if (subsystem_name)
2852 fprintf (file, "\t(%s)", subsystem_name);
2853 fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
2854 if (i->DllCharacteristics)
2856 unsigned short dllch = i->DllCharacteristics;
2857 const char *indent = "\t\t\t\t\t";
2859 if (dllch & IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA)
2860 fprintf (file, "%sHIGH_ENTROPY_VA\n", indent);
2861 if (dllch & IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE)
2862 fprintf (file, "%sDYNAMIC_BASE\n", indent);
2863 if (dllch & IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY)
2864 fprintf (file, "%sFORCE_INTEGRITY\n", indent);
2865 if (dllch & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT)
2866 fprintf (file, "%sNX_COMPAT\n", indent);
2867 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_ISOLATION)
2868 fprintf (file, "%sNO_ISOLATION\n", indent);
2869 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_SEH)
2870 fprintf (file, "%sNO_SEH\n", indent);
2871 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_BIND)
2872 fprintf (file, "%sNO_BIND\n", indent);
2873 if (dllch & IMAGE_DLLCHARACTERISTICS_APPCONTAINER)
2874 fprintf (file, "%sAPPCONTAINER\n", indent);
2875 if (dllch & IMAGE_DLLCHARACTERISTICS_WDM_DRIVER)
2876 fprintf (file, "%sWDM_DRIVER\n", indent);
2877 if (dllch & IMAGE_DLLCHARACTERISTICS_GUARD_CF)
2878 fprintf (file, "%sGUARD_CF\n", indent);
2879 if (dllch & IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE)
2880 fprintf (file, "%sTERMINAL_SERVICE_AWARE\n", indent);
2882 fprintf (file, "SizeOfStackReserve\t");
2883 bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
2884 fprintf (file, "\nSizeOfStackCommit\t");
2885 bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
2886 fprintf (file, "\nSizeOfHeapReserve\t");
2887 bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
2888 fprintf (file, "\nSizeOfHeapCommit\t");
2889 bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
2890 fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
2891 fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
2892 (unsigned long) i->NumberOfRvaAndSizes);
2894 fprintf (file, "\nThe Data Directory\n");
2895 for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
2897 fprintf (file, "Entry %1x ", j);
2898 bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
2899 fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
2900 fprintf (file, "%s\n", dir_names[j]);
2903 pe_print_idata (abfd, vfile);
2904 pe_print_edata (abfd, vfile);
2905 if (bfd_coff_have_print_pdata (abfd))
2906 bfd_coff_print_pdata (abfd, vfile);
2907 else
2908 pe_print_pdata (abfd, vfile);
2909 pe_print_reloc (abfd, vfile);
2910 pe_print_debugdata (abfd, file);
2912 rsrc_print_section (abfd, vfile);
2914 return true;
2917 static bool
2918 is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
2920 bfd_vma addr = * (bfd_vma *) obj;
2921 return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
2924 static asection *
2925 find_section_by_vma (bfd *abfd, bfd_vma addr)
2927 return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
2930 /* Copy any private info we understand from the input bfd
2931 to the output bfd. */
2933 bool
2934 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
2936 pe_data_type *ipe, *ope;
2938 /* One day we may try to grok other private data. */
2939 if (ibfd->xvec->flavour != bfd_target_coff_flavour
2940 || obfd->xvec->flavour != bfd_target_coff_flavour)
2941 return true;
2943 ipe = pe_data (ibfd);
2944 ope = pe_data (obfd);
2946 /* pe_opthdr is copied in copy_object. */
2947 ope->dll = ipe->dll;
2949 /* Don't copy input subsystem if output is different from input. */
2950 if (obfd->xvec != ibfd->xvec)
2951 ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
2953 /* For strip: if we removed .reloc, we'll make a real mess of things
2954 if we don't remove this entry as well. */
2955 if (! pe_data (obfd)->has_reloc_section)
2957 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
2958 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
2961 /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
2962 But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
2963 won't be added. */
2964 if (! pe_data (ibfd)->has_reloc_section
2965 && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
2966 pe_data (obfd)->dont_strip_reloc = 1;
2968 memcpy (ope->dos_message, ipe->dos_message, sizeof (ope->dos_message));
2970 /* The file offsets contained in the debug directory need rewriting. */
2971 if (ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size != 0)
2973 bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
2974 + ope->pe_opthdr.ImageBase;
2975 /* In particular a .buildid section may overlap (in VA space) with
2976 whatever section comes ahead of it (largely because of section->size
2977 representing s_size, not virt_size). Therefore don't look for the
2978 section containing the first byte, but for that covering the last
2979 one. */
2980 bfd_vma last = addr + ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size - 1;
2981 asection *section = find_section_by_vma (obfd, last);
2982 bfd_byte *data;
2984 /* PR 17512: file: 0f15796a. */
2985 if (section && addr < section->vma)
2987 /* xgettext:c-format */
2988 _bfd_error_handler
2989 (_("%pB: Data Directory (%lx bytes at %" PRIx64 ") "
2990 "extends across section boundary at %" PRIx64),
2991 obfd, ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size,
2992 (uint64_t) addr, (uint64_t) section->vma);
2993 return false;
2996 if (section && bfd_malloc_and_get_section (obfd, section, &data))
2998 unsigned int i;
2999 struct external_IMAGE_DEBUG_DIRECTORY *dd =
3000 (struct external_IMAGE_DEBUG_DIRECTORY *)(data + (addr - section->vma));
3002 for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
3003 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
3005 asection *ddsection;
3006 struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
3007 struct internal_IMAGE_DEBUG_DIRECTORY idd;
3009 _bfd_XXi_swap_debugdir_in (obfd, edd, &idd);
3011 if (idd.AddressOfRawData == 0)
3012 continue; /* RVA 0 means only offset is valid, not handled yet. */
3014 ddsection = find_section_by_vma (obfd, idd.AddressOfRawData + ope->pe_opthdr.ImageBase);
3015 if (!ddsection)
3016 continue; /* Not in a section! */
3018 idd.PointerToRawData = ddsection->filepos + (idd.AddressOfRawData
3019 + ope->pe_opthdr.ImageBase) - ddsection->vma;
3021 _bfd_XXi_swap_debugdir_out (obfd, &idd, edd);
3024 if (!bfd_set_section_contents (obfd, section, data, 0, section->size))
3026 _bfd_error_handler (_("failed to update file offsets in debug directory"));
3027 free (data);
3028 return false;
3030 free (data);
3032 else if (section)
3034 _bfd_error_handler (_("%pB: failed to read debug data section"), obfd);
3035 return false;
3039 return true;
3042 /* Copy private section data. */
3044 bool
3045 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
3046 asection *isec,
3047 bfd *obfd,
3048 asection *osec)
3050 if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
3051 || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
3052 return true;
3054 if (coff_section_data (ibfd, isec) != NULL
3055 && pei_section_data (ibfd, isec) != NULL)
3057 if (coff_section_data (obfd, osec) == NULL)
3059 size_t amt = sizeof (struct coff_section_tdata);
3060 osec->used_by_bfd = bfd_zalloc (obfd, amt);
3061 if (osec->used_by_bfd == NULL)
3062 return false;
3065 if (pei_section_data (obfd, osec) == NULL)
3067 size_t amt = sizeof (struct pei_section_tdata);
3068 coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
3069 if (coff_section_data (obfd, osec)->tdata == NULL)
3070 return false;
3073 pei_section_data (obfd, osec)->virt_size =
3074 pei_section_data (ibfd, isec)->virt_size;
3075 pei_section_data (obfd, osec)->pe_flags =
3076 pei_section_data (ibfd, isec)->pe_flags;
3079 return true;
3082 void
3083 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
3085 coff_get_symbol_info (abfd, symbol, ret);
3088 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
3089 static int
3090 sort_x64_pdata (const void *l, const void *r)
3092 const char *lp = (const char *) l;
3093 const char *rp = (const char *) r;
3094 bfd_vma vl, vr;
3095 vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
3096 if (vl != vr)
3097 return (vl < vr ? -1 : 1);
3098 /* We compare just begin address. */
3099 return 0;
3101 #endif
3103 /* Functions to process a .rsrc section. */
3105 static unsigned int sizeof_leaves;
3106 static unsigned int sizeof_strings;
3107 static unsigned int sizeof_tables_and_entries;
3109 static bfd_byte *
3110 rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
3112 static bfd_byte *
3113 rsrc_count_entries (bfd *abfd,
3114 bool is_name,
3115 bfd_byte *datastart,
3116 bfd_byte *data,
3117 bfd_byte *dataend,
3118 bfd_vma rva_bias)
3120 unsigned long entry, addr, size;
3122 if (data + 8 >= dataend)
3123 return dataend + 1;
3125 if (is_name)
3127 bfd_byte * name;
3129 entry = (long) bfd_get_32 (abfd, data);
3131 if (HighBitSet (entry))
3132 name = datastart + WithoutHighBit (entry);
3133 else
3134 name = datastart + entry - rva_bias;
3136 if (name + 2 >= dataend || name < datastart)
3137 return dataend + 1;
3139 unsigned int len = bfd_get_16 (abfd, name);
3140 if (len == 0 || len > 256)
3141 return dataend + 1;
3144 entry = (long) bfd_get_32 (abfd, data + 4);
3146 if (HighBitSet (entry))
3148 data = datastart + WithoutHighBit (entry);
3150 if (data <= datastart || data >= dataend)
3151 return dataend + 1;
3153 return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
3156 if (datastart + entry + 16 >= dataend)
3157 return dataend + 1;
3159 addr = (long) bfd_get_32 (abfd, datastart + entry);
3160 size = (long) bfd_get_32 (abfd, datastart + entry + 4);
3162 return datastart + addr - rva_bias + size;
3165 static bfd_byte *
3166 rsrc_count_directory (bfd * abfd,
3167 bfd_byte * datastart,
3168 bfd_byte * data,
3169 bfd_byte * dataend,
3170 bfd_vma rva_bias)
3172 unsigned int num_entries, num_ids;
3173 bfd_byte * highest_data = data;
3175 if (data + 16 >= dataend)
3176 return dataend + 1;
3178 num_entries = (int) bfd_get_16 (abfd, data + 12);
3179 num_ids = (int) bfd_get_16 (abfd, data + 14);
3181 num_entries += num_ids;
3183 data += 16;
3185 while (num_entries --)
3187 bfd_byte * entry_end;
3189 entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
3190 datastart, data, dataend, rva_bias);
3191 data += 8;
3192 highest_data = max (highest_data, entry_end);
3193 if (entry_end >= dataend)
3194 break;
3197 return max (highest_data, data);
3200 typedef struct rsrc_dir_chain
3202 unsigned int num_entries;
3203 struct rsrc_entry * first_entry;
3204 struct rsrc_entry * last_entry;
3205 } rsrc_dir_chain;
3207 typedef struct rsrc_directory
3209 unsigned int characteristics;
3210 unsigned int time;
3211 unsigned int major;
3212 unsigned int minor;
3214 rsrc_dir_chain names;
3215 rsrc_dir_chain ids;
3217 struct rsrc_entry * entry;
3218 } rsrc_directory;
3220 typedef struct rsrc_string
3222 unsigned int len;
3223 bfd_byte * string;
3224 } rsrc_string;
3226 typedef struct rsrc_leaf
3228 unsigned int size;
3229 unsigned int codepage;
3230 bfd_byte * data;
3231 } rsrc_leaf;
3233 typedef struct rsrc_entry
3235 bool is_name;
3236 union
3238 unsigned int id;
3239 struct rsrc_string name;
3240 } name_id;
3242 bool is_dir;
3243 union
3245 struct rsrc_directory * directory;
3246 struct rsrc_leaf * leaf;
3247 } value;
3249 struct rsrc_entry * next_entry;
3250 struct rsrc_directory * parent;
3251 } rsrc_entry;
3253 static bfd_byte *
3254 rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
3255 bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
3257 static bfd_byte *
3258 rsrc_parse_entry (bfd *abfd,
3259 bool is_name,
3260 rsrc_entry *entry,
3261 bfd_byte *datastart,
3262 bfd_byte * data,
3263 bfd_byte *dataend,
3264 bfd_vma rva_bias,
3265 rsrc_directory *parent)
3267 unsigned long val, addr, size;
3269 val = bfd_get_32 (abfd, data);
3271 entry->parent = parent;
3272 entry->is_name = is_name;
3274 if (is_name)
3276 bfd_byte * address;
3278 if (HighBitSet (val))
3280 val = WithoutHighBit (val);
3282 address = datastart + val;
3284 else
3286 address = datastart + val - rva_bias;
3289 if (address + 3 > dataend)
3290 return dataend;
3292 entry->name_id.name.len = bfd_get_16 (abfd, address);
3293 entry->name_id.name.string = address + 2;
3295 else
3296 entry->name_id.id = val;
3298 val = bfd_get_32 (abfd, data + 4);
3300 if (HighBitSet (val))
3302 entry->is_dir = true;
3303 entry->value.directory = bfd_malloc (sizeof * entry->value.directory);
3304 if (entry->value.directory == NULL)
3305 return dataend;
3307 return rsrc_parse_directory (abfd, entry->value.directory,
3308 datastart,
3309 datastart + WithoutHighBit (val),
3310 dataend, rva_bias, entry);
3313 entry->is_dir = false;
3314 entry->value.leaf = bfd_malloc (sizeof * entry->value.leaf);
3315 if (entry->value.leaf == NULL)
3316 return dataend;
3318 data = datastart + val;
3319 if (data < datastart || data >= dataend)
3320 return dataend;
3322 addr = bfd_get_32 (abfd, data);
3323 size = entry->value.leaf->size = bfd_get_32 (abfd, data + 4);
3324 entry->value.leaf->codepage = bfd_get_32 (abfd, data + 8);
3325 /* FIXME: We assume that the reserved field (data + 12) is OK. */
3327 entry->value.leaf->data = bfd_malloc (size);
3328 if (entry->value.leaf->data == NULL)
3329 return dataend;
3331 memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
3332 return datastart + (addr - rva_bias) + size;
3335 static bfd_byte *
3336 rsrc_parse_entries (bfd *abfd,
3337 rsrc_dir_chain *chain,
3338 bool is_name,
3339 bfd_byte *highest_data,
3340 bfd_byte *datastart,
3341 bfd_byte *data,
3342 bfd_byte *dataend,
3343 bfd_vma rva_bias,
3344 rsrc_directory *parent)
3346 unsigned int i;
3347 rsrc_entry * entry;
3349 if (chain->num_entries == 0)
3351 chain->first_entry = chain->last_entry = NULL;
3352 return highest_data;
3355 entry = bfd_malloc (sizeof * entry);
3356 if (entry == NULL)
3357 return dataend;
3359 chain->first_entry = entry;
3361 for (i = chain->num_entries; i--;)
3363 bfd_byte * entry_end;
3365 entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
3366 data, dataend, rva_bias, parent);
3367 data += 8;
3368 highest_data = max (entry_end, highest_data);
3369 if (entry_end > dataend)
3370 return dataend;
3372 if (i)
3374 entry->next_entry = bfd_malloc (sizeof * entry);
3375 entry = entry->next_entry;
3376 if (entry == NULL)
3377 return dataend;
3379 else
3380 entry->next_entry = NULL;
3383 chain->last_entry = entry;
3385 return highest_data;
3388 static bfd_byte *
3389 rsrc_parse_directory (bfd * abfd,
3390 rsrc_directory * table,
3391 bfd_byte * datastart,
3392 bfd_byte * data,
3393 bfd_byte * dataend,
3394 bfd_vma rva_bias,
3395 rsrc_entry * entry)
3397 bfd_byte * highest_data = data;
3399 if (table == NULL)
3400 return dataend;
3402 table->characteristics = bfd_get_32 (abfd, data);
3403 table->time = bfd_get_32 (abfd, data + 4);
3404 table->major = bfd_get_16 (abfd, data + 8);
3405 table->minor = bfd_get_16 (abfd, data + 10);
3406 table->names.num_entries = bfd_get_16 (abfd, data + 12);
3407 table->ids.num_entries = bfd_get_16 (abfd, data + 14);
3408 table->entry = entry;
3410 data += 16;
3412 highest_data = rsrc_parse_entries (abfd, & table->names, true, data,
3413 datastart, data, dataend, rva_bias, table);
3414 data += table->names.num_entries * 8;
3416 highest_data = rsrc_parse_entries (abfd, & table->ids, false, highest_data,
3417 datastart, data, dataend, rva_bias, table);
3418 data += table->ids.num_entries * 8;
3420 return max (highest_data, data);
3423 typedef struct rsrc_write_data
3425 bfd * abfd;
3426 bfd_byte * datastart;
3427 bfd_byte * next_table;
3428 bfd_byte * next_leaf;
3429 bfd_byte * next_string;
3430 bfd_byte * next_data;
3431 bfd_vma rva_bias;
3432 } rsrc_write_data;
3434 static void
3435 rsrc_write_string (rsrc_write_data * data,
3436 rsrc_string * string)
3438 bfd_put_16 (data->abfd, string->len, data->next_string);
3439 memcpy (data->next_string + 2, string->string, string->len * 2);
3440 data->next_string += (string->len + 1) * 2;
3443 static inline unsigned int
3444 rsrc_compute_rva (rsrc_write_data * data,
3445 bfd_byte * addr)
3447 return (addr - data->datastart) + data->rva_bias;
3450 static void
3451 rsrc_write_leaf (rsrc_write_data * data,
3452 rsrc_leaf * leaf)
3454 bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
3455 data->next_leaf);
3456 bfd_put_32 (data->abfd, leaf->size, data->next_leaf + 4);
3457 bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
3458 bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
3459 data->next_leaf += 16;
3461 memcpy (data->next_data, leaf->data, leaf->size);
3462 /* An undocumented feature of Windows resources is that each unit
3463 of raw data is 8-byte aligned... */
3464 data->next_data += ((leaf->size + 7) & ~7);
3467 static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
3469 static void
3470 rsrc_write_entry (rsrc_write_data * data,
3471 bfd_byte * where,
3472 rsrc_entry * entry)
3474 if (entry->is_name)
3476 bfd_put_32 (data->abfd,
3477 SetHighBit (data->next_string - data->datastart),
3478 where);
3479 rsrc_write_string (data, & entry->name_id.name);
3481 else
3482 bfd_put_32 (data->abfd, entry->name_id.id, where);
3484 if (entry->is_dir)
3486 bfd_put_32 (data->abfd,
3487 SetHighBit (data->next_table - data->datastart),
3488 where + 4);
3489 rsrc_write_directory (data, entry->value.directory);
3491 else
3493 bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
3494 rsrc_write_leaf (data, entry->value.leaf);
3498 static void
3499 rsrc_compute_region_sizes (rsrc_directory * dir)
3501 struct rsrc_entry * entry;
3503 if (dir == NULL)
3504 return;
3506 sizeof_tables_and_entries += 16;
3508 for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
3510 sizeof_tables_and_entries += 8;
3512 sizeof_strings += (entry->name_id.name.len + 1) * 2;
3514 if (entry->is_dir)
3515 rsrc_compute_region_sizes (entry->value.directory);
3516 else
3517 sizeof_leaves += 16;
3520 for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
3522 sizeof_tables_and_entries += 8;
3524 if (entry->is_dir)
3525 rsrc_compute_region_sizes (entry->value.directory);
3526 else
3527 sizeof_leaves += 16;
3531 static void
3532 rsrc_write_directory (rsrc_write_data * data,
3533 rsrc_directory * dir)
3535 rsrc_entry * entry;
3536 unsigned int i;
3537 bfd_byte * next_entry;
3538 bfd_byte * nt;
3540 bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
3541 bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
3542 bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
3543 bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
3544 bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
3545 bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
3547 /* Compute where the entries and the next table will be placed. */
3548 next_entry = data->next_table + 16;
3549 data->next_table = next_entry + (dir->names.num_entries * 8)
3550 + (dir->ids.num_entries * 8);
3551 nt = data->next_table;
3553 /* Write the entries. */
3554 for (i = dir->names.num_entries, entry = dir->names.first_entry;
3555 i > 0 && entry != NULL;
3556 i--, entry = entry->next_entry)
3558 BFD_ASSERT (entry->is_name);
3559 rsrc_write_entry (data, next_entry, entry);
3560 next_entry += 8;
3562 BFD_ASSERT (i == 0);
3563 BFD_ASSERT (entry == NULL);
3565 for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
3566 i > 0 && entry != NULL;
3567 i--, entry = entry->next_entry)
3569 BFD_ASSERT (! entry->is_name);
3570 rsrc_write_entry (data, next_entry, entry);
3571 next_entry += 8;
3573 BFD_ASSERT (i == 0);
3574 BFD_ASSERT (entry == NULL);
3575 BFD_ASSERT (nt == next_entry);
3578 #if ! defined __CYGWIN__ && ! defined __MINGW32__
3579 /* Return the length (number of units) of the first character in S,
3580 putting its 'ucs4_t' representation in *PUC. */
3582 static unsigned int
3583 u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
3585 unsigned short c = * s;
3587 if (c < 0xd800 || c >= 0xe000)
3589 *puc = c;
3590 return 1;
3593 if (c < 0xdc00)
3595 if (n >= 2)
3597 if (s[1] >= 0xdc00 && s[1] < 0xe000)
3599 *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
3600 return 2;
3603 else
3605 /* Incomplete multibyte character. */
3606 *puc = 0xfffd;
3607 return n;
3611 /* Invalid multibyte character. */
3612 *puc = 0xfffd;
3613 return 1;
3615 #endif /* not Cygwin/Mingw */
3617 /* Perform a comparison of two entries. */
3618 static signed int
3619 rsrc_cmp (bool is_name, rsrc_entry * a, rsrc_entry * b)
3621 signed int res;
3622 bfd_byte * astring;
3623 unsigned int alen;
3624 bfd_byte * bstring;
3625 unsigned int blen;
3627 if (! is_name)
3628 return a->name_id.id - b->name_id.id;
3630 /* We have to perform a case insenstive, unicode string comparison... */
3631 astring = a->name_id.name.string;
3632 alen = a->name_id.name.len;
3633 bstring = b->name_id.name.string;
3634 blen = b->name_id.name.len;
3636 #if defined __CYGWIN__ || defined __MINGW32__
3637 /* Under Windows hosts (both Cygwin and Mingw types),
3638 unicode == UTF-16 == wchar_t. The case insensitive string comparison
3639 function however goes by different names in the two environments... */
3641 #undef rscpcmp
3642 #ifdef __CYGWIN__
3643 #define rscpcmp wcsncasecmp
3644 #endif
3645 #ifdef __MINGW32__
3646 #define rscpcmp wcsnicmp
3647 #endif
3649 res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
3650 min (alen, blen));
3652 #else
3654 unsigned int i;
3656 res = 0;
3657 for (i = min (alen, blen); i--; astring += 2, bstring += 2)
3659 wint_t awc;
3660 wint_t bwc;
3662 /* Convert UTF-16 unicode characters into wchar_t characters
3663 so that we can then perform a case insensitive comparison. */
3664 unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
3665 unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
3667 if (Alen != Blen)
3668 return Alen - Blen;
3670 awc = towlower (awc);
3671 bwc = towlower (bwc);
3673 res = awc - bwc;
3674 if (res)
3675 break;
3678 #endif
3680 if (res == 0)
3681 res = alen - blen;
3683 return res;
3686 static void
3687 rsrc_print_name (char * buffer, rsrc_string string)
3689 unsigned int i;
3690 bfd_byte * name = string.string;
3692 for (i = string.len; i--; name += 2)
3693 sprintf (buffer + strlen (buffer), "%.1s", name);
3696 static const char *
3697 rsrc_resource_name (rsrc_entry *entry, rsrc_directory *dir, char *buffer)
3699 bool is_string = false;
3701 buffer[0] = 0;
3703 if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
3704 && dir->entry->parent->entry != NULL)
3706 strcpy (buffer, "type: ");
3707 if (dir->entry->parent->entry->is_name)
3708 rsrc_print_name (buffer + strlen (buffer),
3709 dir->entry->parent->entry->name_id.name);
3710 else
3712 unsigned int id = dir->entry->parent->entry->name_id.id;
3714 sprintf (buffer + strlen (buffer), "%x", id);
3715 switch (id)
3717 case 1: strcat (buffer, " (CURSOR)"); break;
3718 case 2: strcat (buffer, " (BITMAP)"); break;
3719 case 3: strcat (buffer, " (ICON)"); break;
3720 case 4: strcat (buffer, " (MENU)"); break;
3721 case 5: strcat (buffer, " (DIALOG)"); break;
3722 case 6: strcat (buffer, " (STRING)"); is_string = true; break;
3723 case 7: strcat (buffer, " (FONTDIR)"); break;
3724 case 8: strcat (buffer, " (FONT)"); break;
3725 case 9: strcat (buffer, " (ACCELERATOR)"); break;
3726 case 10: strcat (buffer, " (RCDATA)"); break;
3727 case 11: strcat (buffer, " (MESSAGETABLE)"); break;
3728 case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
3729 case 14: strcat (buffer, " (GROUP_ICON)"); break;
3730 case 16: strcat (buffer, " (VERSION)"); break;
3731 case 17: strcat (buffer, " (DLGINCLUDE)"); break;
3732 case 19: strcat (buffer, " (PLUGPLAY)"); break;
3733 case 20: strcat (buffer, " (VXD)"); break;
3734 case 21: strcat (buffer, " (ANICURSOR)"); break;
3735 case 22: strcat (buffer, " (ANIICON)"); break;
3736 case 23: strcat (buffer, " (HTML)"); break;
3737 case 24: strcat (buffer, " (MANIFEST)"); break;
3738 case 240: strcat (buffer, " (DLGINIT)"); break;
3739 case 241: strcat (buffer, " (TOOLBAR)"); break;
3744 if (dir != NULL && dir->entry != NULL)
3746 strcat (buffer, " name: ");
3747 if (dir->entry->is_name)
3748 rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
3749 else
3751 unsigned int id = dir->entry->name_id.id;
3753 sprintf (buffer + strlen (buffer), "%x", id);
3755 if (is_string)
3756 sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
3757 (id - 1) << 4, (id << 4) - 1);
3761 if (entry != NULL)
3763 strcat (buffer, " lang: ");
3765 if (entry->is_name)
3766 rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
3767 else
3768 sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
3771 return buffer;
3774 /* *sigh* Windows resource strings are special. Only the top 28-bits of
3775 their ID is stored in the NAME entry. The bottom four bits are used as
3776 an index into unicode string table that makes up the data of the leaf.
3777 So identical type-name-lang string resources may not actually be
3778 identical at all.
3780 This function is called when we have detected two string resources with
3781 match top-28-bit IDs. We have to scan the string tables inside the leaves
3782 and discover if there are any real collisions. If there are then we report
3783 them and return FALSE. Otherwise we copy any strings from B into A and
3784 then return TRUE. */
3786 static bool
3787 rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
3788 rsrc_entry * b ATTRIBUTE_UNUSED)
3790 unsigned int copy_needed = 0;
3791 unsigned int i;
3792 bfd_byte * astring;
3793 bfd_byte * bstring;
3794 bfd_byte * new_data;
3795 bfd_byte * nstring;
3797 /* Step one: Find out what we have to do. */
3798 BFD_ASSERT (! a->is_dir);
3799 astring = a->value.leaf->data;
3801 BFD_ASSERT (! b->is_dir);
3802 bstring = b->value.leaf->data;
3804 for (i = 0; i < 16; i++)
3806 unsigned int alen = astring[0] + (astring[1] << 8);
3807 unsigned int blen = bstring[0] + (bstring[1] << 8);
3809 if (alen == 0)
3811 copy_needed += blen * 2;
3813 else if (blen == 0)
3815 else if (alen != blen)
3816 /* FIXME: Should we continue the loop in order to report other duplicates ? */
3817 break;
3818 /* alen == blen != 0. We might have two identical strings. If so we
3819 can ignore the second one. There is no need for wchar_t vs UTF-16
3820 theatrics here - we are only interested in (case sensitive) equality. */
3821 else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
3822 break;
3824 astring += (alen + 1) * 2;
3825 bstring += (blen + 1) * 2;
3828 if (i != 16)
3830 if (a->parent != NULL
3831 && a->parent->entry != NULL
3832 && !a->parent->entry->is_name)
3833 _bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
3834 ((a->parent->entry->name_id.id - 1) << 4) + i);
3835 return false;
3838 if (copy_needed == 0)
3839 return true;
3841 /* If we reach here then A and B must both have non-colliding strings.
3842 (We never get string resources with fully empty string tables).
3843 We need to allocate an extra COPY_NEEDED bytes in A and then bring
3844 in B's strings. */
3845 new_data = bfd_malloc (a->value.leaf->size + copy_needed);
3846 if (new_data == NULL)
3847 return false;
3849 nstring = new_data;
3850 astring = a->value.leaf->data;
3851 bstring = b->value.leaf->data;
3853 for (i = 0; i < 16; i++)
3855 unsigned int alen = astring[0] + (astring[1] << 8);
3856 unsigned int blen = bstring[0] + (bstring[1] << 8);
3858 if (alen != 0)
3860 memcpy (nstring, astring, (alen + 1) * 2);
3861 nstring += (alen + 1) * 2;
3863 else if (blen != 0)
3865 memcpy (nstring, bstring, (blen + 1) * 2);
3866 nstring += (blen + 1) * 2;
3868 else
3870 * nstring++ = 0;
3871 * nstring++ = 0;
3874 astring += (alen + 1) * 2;
3875 bstring += (blen + 1) * 2;
3878 BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
3880 free (a->value.leaf->data);
3881 a->value.leaf->data = new_data;
3882 a->value.leaf->size += copy_needed;
3884 return true;
3887 static void rsrc_merge (rsrc_entry *, rsrc_entry *);
3889 /* Sort the entries in given part of the directory.
3890 We use an old fashioned bubble sort because we are dealing
3891 with lists and we want to handle matches specially. */
3893 static void
3894 rsrc_sort_entries (rsrc_dir_chain *chain,
3895 bool is_name,
3896 rsrc_directory *dir)
3898 rsrc_entry * entry;
3899 rsrc_entry * next;
3900 rsrc_entry ** points_to_entry;
3901 bool swapped;
3903 if (chain->num_entries < 2)
3904 return;
3908 swapped = false;
3909 points_to_entry = & chain->first_entry;
3910 entry = * points_to_entry;
3911 next = entry->next_entry;
3915 signed int cmp = rsrc_cmp (is_name, entry, next);
3917 if (cmp > 0)
3919 entry->next_entry = next->next_entry;
3920 next->next_entry = entry;
3921 * points_to_entry = next;
3922 points_to_entry = & next->next_entry;
3923 next = entry->next_entry;
3924 swapped = true;
3926 else if (cmp == 0)
3928 if (entry->is_dir && next->is_dir)
3930 /* When we encounter identical directory entries we have to
3931 merge them together. The exception to this rule is for
3932 resource manifests - there can only be one of these,
3933 even if they differ in language. Zero-language manifests
3934 are assumed to be default manifests (provided by the
3935 Cygwin/MinGW build system) and these can be silently dropped,
3936 unless that would reduce the number of manifests to zero.
3937 There should only ever be one non-zero lang manifest -
3938 if there are more it is an error. A non-zero lang
3939 manifest takes precedence over a default manifest. */
3940 if (!entry->is_name
3941 && entry->name_id.id == 1
3942 && dir != NULL
3943 && dir->entry != NULL
3944 && !dir->entry->is_name
3945 && dir->entry->name_id.id == 0x18)
3947 if (next->value.directory->names.num_entries == 0
3948 && next->value.directory->ids.num_entries == 1
3949 && !next->value.directory->ids.first_entry->is_name
3950 && next->value.directory->ids.first_entry->name_id.id == 0)
3951 /* Fall through so that NEXT is dropped. */
3953 else if (entry->value.directory->names.num_entries == 0
3954 && entry->value.directory->ids.num_entries == 1
3955 && !entry->value.directory->ids.first_entry->is_name
3956 && entry->value.directory->ids.first_entry->name_id.id == 0)
3958 /* Swap ENTRY and NEXT. Then fall through so that the old ENTRY is dropped. */
3959 entry->next_entry = next->next_entry;
3960 next->next_entry = entry;
3961 * points_to_entry = next;
3962 points_to_entry = & next->next_entry;
3963 next = entry->next_entry;
3964 swapped = true;
3966 else
3968 _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
3969 bfd_set_error (bfd_error_file_truncated);
3970 return;
3973 /* Unhook NEXT from the chain. */
3974 /* FIXME: memory loss here. */
3975 entry->next_entry = next->next_entry;
3976 chain->num_entries --;
3977 if (chain->num_entries < 2)
3978 return;
3979 next = next->next_entry;
3981 else
3982 rsrc_merge (entry, next);
3984 else if (entry->is_dir != next->is_dir)
3986 _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
3987 bfd_set_error (bfd_error_file_truncated);
3988 return;
3990 else
3992 /* Otherwise with identical leaves we issue an error
3993 message - because there should never be duplicates.
3994 The exception is Type 18/Name 1/Lang 0 which is the
3995 defaul manifest - this can just be dropped. */
3996 if (!entry->is_name
3997 && entry->name_id.id == 0
3998 && dir != NULL
3999 && dir->entry != NULL
4000 && !dir->entry->is_name
4001 && dir->entry->name_id.id == 1
4002 && dir->entry->parent != NULL
4003 && dir->entry->parent->entry != NULL
4004 && !dir->entry->parent->entry->is_name
4005 && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
4007 else if (dir != NULL
4008 && dir->entry != NULL
4009 && dir->entry->parent != NULL
4010 && dir->entry->parent->entry != NULL
4011 && !dir->entry->parent->entry->is_name
4012 && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
4014 /* Strings need special handling. */
4015 if (! rsrc_merge_string_entries (entry, next))
4017 /* _bfd_error_handler should have been called inside merge_strings. */
4018 bfd_set_error (bfd_error_file_truncated);
4019 return;
4022 else
4024 if (dir == NULL
4025 || dir->entry == NULL
4026 || dir->entry->parent == NULL
4027 || dir->entry->parent->entry == NULL)
4028 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
4029 else
4031 char buff[256];
4033 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
4034 rsrc_resource_name (entry, dir, buff));
4036 bfd_set_error (bfd_error_file_truncated);
4037 return;
4041 /* Unhook NEXT from the chain. */
4042 entry->next_entry = next->next_entry;
4043 chain->num_entries --;
4044 if (chain->num_entries < 2)
4045 return;
4046 next = next->next_entry;
4048 else
4050 points_to_entry = & entry->next_entry;
4051 entry = next;
4052 next = next->next_entry;
4055 while (next);
4057 chain->last_entry = entry;
4059 while (swapped);
4062 /* Attach B's chain onto A. */
4063 static void
4064 rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
4066 if (bchain->num_entries == 0)
4067 return;
4069 achain->num_entries += bchain->num_entries;
4071 if (achain->first_entry == NULL)
4073 achain->first_entry = bchain->first_entry;
4074 achain->last_entry = bchain->last_entry;
4076 else
4078 achain->last_entry->next_entry = bchain->first_entry;
4079 achain->last_entry = bchain->last_entry;
4082 bchain->num_entries = 0;
4083 bchain->first_entry = bchain->last_entry = NULL;
4086 static void
4087 rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
4089 rsrc_directory * adir;
4090 rsrc_directory * bdir;
4092 BFD_ASSERT (a->is_dir);
4093 BFD_ASSERT (b->is_dir);
4095 adir = a->value.directory;
4096 bdir = b->value.directory;
4098 if (adir->characteristics != bdir->characteristics)
4100 _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics"));
4101 bfd_set_error (bfd_error_file_truncated);
4102 return;
4105 if (adir->major != bdir->major || adir->minor != bdir->minor)
4107 _bfd_error_handler (_(".rsrc merge failure: differing directory versions"));
4108 bfd_set_error (bfd_error_file_truncated);
4109 return;
4112 /* Attach B's name chain to A. */
4113 rsrc_attach_chain (& adir->names, & bdir->names);
4115 /* Attach B's ID chain to A. */
4116 rsrc_attach_chain (& adir->ids, & bdir->ids);
4118 /* Now sort A's entries. */
4119 rsrc_sort_entries (& adir->names, true, adir);
4120 rsrc_sort_entries (& adir->ids, false, adir);
4123 /* Check the .rsrc section. If it contains multiple concatenated
4124 resources then we must merge them properly. Otherwise Windows
4125 will ignore all but the first set. */
4127 static void
4128 rsrc_process_section (bfd * abfd,
4129 struct coff_final_link_info * pfinfo)
4131 rsrc_directory new_table;
4132 bfd_size_type size;
4133 asection * sec;
4134 pe_data_type * pe;
4135 bfd_vma rva_bias;
4136 bfd_byte * data;
4137 bfd_byte * datastart;
4138 bfd_byte * dataend;
4139 bfd_byte * new_data;
4140 unsigned int num_resource_sets;
4141 rsrc_directory * type_tables;
4142 rsrc_write_data write_data;
4143 unsigned int indx;
4144 bfd * input;
4145 unsigned int num_input_rsrc = 0;
4146 unsigned int max_num_input_rsrc = 4;
4147 ptrdiff_t * rsrc_sizes = NULL;
4149 new_table.names.num_entries = 0;
4150 new_table.ids.num_entries = 0;
4152 sec = bfd_get_section_by_name (abfd, ".rsrc");
4153 if (sec == NULL || (size = sec->rawsize) == 0)
4154 return;
4156 pe = pe_data (abfd);
4157 if (pe == NULL)
4158 return;
4160 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4162 data = bfd_malloc (size);
4163 if (data == NULL)
4164 return;
4166 datastart = data;
4168 if (! bfd_get_section_contents (abfd, sec, data, 0, size))
4169 goto end;
4171 /* Step zero: Scan the input bfds looking for .rsrc sections and record
4172 their lengths. Note - we rely upon the fact that the linker script
4173 does *not* sort the input .rsrc sections, so that the order in the
4174 linkinfo list matches the order in the output .rsrc section.
4176 We need to know the lengths because each input .rsrc section has padding
4177 at the end of a variable amount. (It does not appear to be based upon
4178 the section alignment or the file alignment). We need to skip any
4179 padding bytes when parsing the input .rsrc sections. */
4180 rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof * rsrc_sizes);
4181 if (rsrc_sizes == NULL)
4182 goto end;
4184 for (input = pfinfo->info->input_bfds;
4185 input != NULL;
4186 input = input->link.next)
4188 asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
4190 /* PR 18372 - skip discarded .rsrc sections. */
4191 if (rsrc_sec != NULL && !discarded_section (rsrc_sec))
4193 if (num_input_rsrc == max_num_input_rsrc)
4195 max_num_input_rsrc += 10;
4196 rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
4197 * sizeof * rsrc_sizes);
4198 if (rsrc_sizes == NULL)
4199 goto end;
4202 BFD_ASSERT (rsrc_sec->size > 0);
4203 rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
4207 if (num_input_rsrc < 2)
4208 goto end;
4210 /* Step one: Walk the section, computing the size of the tables,
4211 leaves and data and decide if we need to do anything. */
4212 dataend = data + size;
4213 num_resource_sets = 0;
4215 while (data < dataend)
4217 bfd_byte * p = data;
4219 data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
4221 if (data > dataend)
4223 /* Corrupted .rsrc section - cannot merge. */
4224 _bfd_error_handler (_("%pB: .rsrc merge failure: corrupt .rsrc section"),
4225 abfd);
4226 bfd_set_error (bfd_error_file_truncated);
4227 goto end;
4230 if ((data - p) > rsrc_sizes [num_resource_sets])
4232 _bfd_error_handler (_("%pB: .rsrc merge failure: unexpected .rsrc size"),
4233 abfd);
4234 bfd_set_error (bfd_error_file_truncated);
4235 goto end;
4237 /* FIXME: Should we add a check for "data - p" being much smaller
4238 than rsrc_sizes[num_resource_sets] ? */
4240 data = p + rsrc_sizes[num_resource_sets];
4241 rva_bias += data - p;
4242 ++ num_resource_sets;
4244 BFD_ASSERT (num_resource_sets == num_input_rsrc);
4246 /* Step two: Walk the data again, building trees of the resources. */
4247 data = datastart;
4248 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4250 type_tables = bfd_malloc (num_resource_sets * sizeof * type_tables);
4251 if (type_tables == NULL)
4252 goto end;
4254 indx = 0;
4255 while (data < dataend)
4257 bfd_byte * p = data;
4259 (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
4260 dataend, rva_bias, NULL);
4261 data = p + rsrc_sizes[indx];
4262 rva_bias += data - p;
4263 ++ indx;
4265 BFD_ASSERT (indx == num_resource_sets);
4267 /* Step three: Merge the top level tables (there can be only one).
4269 We must ensure that the merged entries are in ascending order.
4271 We also thread the top level table entries from the old tree onto
4272 the new table, so that they can be pulled off later. */
4274 /* FIXME: Should we verify that all type tables are the same ? */
4275 new_table.characteristics = type_tables[0].characteristics;
4276 new_table.time = type_tables[0].time;
4277 new_table.major = type_tables[0].major;
4278 new_table.minor = type_tables[0].minor;
4280 /* Chain the NAME entries onto the table. */
4281 new_table.names.first_entry = NULL;
4282 new_table.names.last_entry = NULL;
4284 for (indx = 0; indx < num_resource_sets; indx++)
4285 rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
4287 rsrc_sort_entries (& new_table.names, true, & new_table);
4289 /* Chain the ID entries onto the table. */
4290 new_table.ids.first_entry = NULL;
4291 new_table.ids.last_entry = NULL;
4293 for (indx = 0; indx < num_resource_sets; indx++)
4294 rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
4296 rsrc_sort_entries (& new_table.ids, false, & new_table);
4298 /* Step four: Create new contents for the .rsrc section. */
4299 /* Step four point one: Compute the size of each region of the .rsrc section.
4300 We do this now, rather than earlier, as the merging above may have dropped
4301 some entries. */
4302 sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
4303 rsrc_compute_region_sizes (& new_table);
4304 /* We increment sizeof_strings to make sure that resource data
4305 starts on an 8-byte boundary. FIXME: Is this correct ? */
4306 sizeof_strings = (sizeof_strings + 7) & ~ 7;
4308 new_data = bfd_zalloc (abfd, size);
4309 if (new_data == NULL)
4310 goto end;
4312 write_data.abfd = abfd;
4313 write_data.datastart = new_data;
4314 write_data.next_table = new_data;
4315 write_data.next_leaf = new_data + sizeof_tables_and_entries;
4316 write_data.next_string = write_data.next_leaf + sizeof_leaves;
4317 write_data.next_data = write_data.next_string + sizeof_strings;
4318 write_data.rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4320 rsrc_write_directory (& write_data, & new_table);
4322 /* Step five: Replace the old contents with the new.
4323 We don't recompute the size as it's too late here to shrink section.
4324 See PR ld/20193 for more details. */
4325 bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
4326 sec->size = sec->rawsize = size;
4328 end:
4329 /* Step six: Free all the memory that we have used. */
4330 /* FIXME: Free the resource tree, if we have one. */
4331 free (datastart);
4332 free (rsrc_sizes);
4335 /* Handle the .idata section and other things that need symbol table
4336 access. */
4338 bool
4339 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
4341 struct coff_link_hash_entry *h1;
4342 struct bfd_link_info *info = pfinfo->info;
4343 bool result = true;
4345 /* There are a few fields that need to be filled in now while we
4346 have symbol table access.
4348 The .idata subsections aren't directly available as sections, but
4349 they are in the symbol table, so get them from there. */
4351 /* The import directory. This is the address of .idata$2, with size
4352 of .idata$2 + .idata$3. */
4353 h1 = coff_link_hash_lookup (coff_hash_table (info),
4354 ".idata$2", false, false, true);
4355 if (h1 != NULL)
4357 /* PR ld/2729: We cannot rely upon all the output sections having been
4358 created properly, so check before referencing them. Issue a warning
4359 message for any sections tht could not be found. */
4360 if ((h1->root.type == bfd_link_hash_defined
4361 || h1->root.type == bfd_link_hash_defweak)
4362 && h1->root.u.def.section != NULL
4363 && h1->root.u.def.section->output_section != NULL)
4364 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
4365 (h1->root.u.def.value
4366 + h1->root.u.def.section->output_section->vma
4367 + h1->root.u.def.section->output_offset);
4368 else
4370 _bfd_error_handler
4371 (_("%pB: unable to fill in DataDictionary[1] because .idata$2 is missing"),
4372 abfd);
4373 result = false;
4376 h1 = coff_link_hash_lookup (coff_hash_table (info),
4377 ".idata$4", false, false, true);
4378 if (h1 != NULL
4379 && (h1->root.type == bfd_link_hash_defined
4380 || h1->root.type == bfd_link_hash_defweak)
4381 && h1->root.u.def.section != NULL
4382 && h1->root.u.def.section->output_section != NULL)
4383 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
4384 ((h1->root.u.def.value
4385 + h1->root.u.def.section->output_section->vma
4386 + h1->root.u.def.section->output_offset)
4387 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
4388 else
4390 _bfd_error_handler
4391 (_("%pB: unable to fill in DataDictionary[1] because .idata$4 is missing"),
4392 abfd);
4393 result = false;
4396 /* The import address table. This is the size/address of
4397 .idata$5. */
4398 h1 = coff_link_hash_lookup (coff_hash_table (info),
4399 ".idata$5", false, false, true);
4400 if (h1 != NULL
4401 && (h1->root.type == bfd_link_hash_defined
4402 || h1->root.type == bfd_link_hash_defweak)
4403 && h1->root.u.def.section != NULL
4404 && h1->root.u.def.section->output_section != NULL)
4405 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4406 (h1->root.u.def.value
4407 + h1->root.u.def.section->output_section->vma
4408 + h1->root.u.def.section->output_offset);
4409 else
4411 _bfd_error_handler
4412 (_("%pB: unable to fill in DataDictionary[12] because .idata$5 is missing"),
4413 abfd);
4414 result = false;
4417 h1 = coff_link_hash_lookup (coff_hash_table (info),
4418 ".idata$6", false, false, true);
4419 if (h1 != NULL
4420 && (h1->root.type == bfd_link_hash_defined
4421 || h1->root.type == bfd_link_hash_defweak)
4422 && h1->root.u.def.section != NULL
4423 && h1->root.u.def.section->output_section != NULL)
4424 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4425 ((h1->root.u.def.value
4426 + h1->root.u.def.section->output_section->vma
4427 + h1->root.u.def.section->output_offset)
4428 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
4429 else
4431 _bfd_error_handler
4432 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
4433 abfd);
4434 result = false;
4437 else
4439 h1 = coff_link_hash_lookup (coff_hash_table (info),
4440 "__IAT_start__", false, false, true);
4441 if (h1 != NULL
4442 && (h1->root.type == bfd_link_hash_defined
4443 || h1->root.type == bfd_link_hash_defweak)
4444 && h1->root.u.def.section != NULL
4445 && h1->root.u.def.section->output_section != NULL)
4447 bfd_vma iat_va;
4449 iat_va =
4450 (h1->root.u.def.value
4451 + h1->root.u.def.section->output_section->vma
4452 + h1->root.u.def.section->output_offset);
4454 h1 = coff_link_hash_lookup (coff_hash_table (info),
4455 "__IAT_end__", false, false, true);
4456 if (h1 != NULL
4457 && (h1->root.type == bfd_link_hash_defined
4458 || h1->root.type == bfd_link_hash_defweak)
4459 && h1->root.u.def.section != NULL
4460 && h1->root.u.def.section->output_section != NULL)
4462 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4463 ((h1->root.u.def.value
4464 + h1->root.u.def.section->output_section->vma
4465 + h1->root.u.def.section->output_offset)
4466 - iat_va);
4467 if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
4468 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4469 iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
4471 else
4473 _bfd_error_handler
4474 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
4475 " because .idata$6 is missing"), abfd);
4476 result = false;
4481 h1 = coff_link_hash_lookup (coff_hash_table (info),
4482 (bfd_get_symbol_leading_char (abfd) != 0
4483 ? "__tls_used" : "_tls_used"),
4484 false, false, true);
4485 if (h1 != NULL)
4487 if ((h1->root.type == bfd_link_hash_defined
4488 || h1->root.type == bfd_link_hash_defweak)
4489 && h1->root.u.def.section != NULL
4490 && h1->root.u.def.section->output_section != NULL)
4491 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
4492 (h1->root.u.def.value
4493 + h1->root.u.def.section->output_section->vma
4494 + h1->root.u.def.section->output_offset
4495 - pe_data (abfd)->pe_opthdr.ImageBase);
4496 else
4498 _bfd_error_handler
4499 (_("%pB: unable to fill in DataDictionary[9] because __tls_used is missing"),
4500 abfd);
4501 result = false;
4503 /* According to PECOFF sepcifications by Microsoft version 8.2
4504 the TLS data directory consists of 4 pointers, followed
4505 by two 4-byte integer. This implies that the total size
4506 is different for 32-bit and 64-bit executables. */
4507 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
4508 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
4509 #else
4510 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
4511 #endif
4514 /* If there is a .pdata section and we have linked pdata finally, we
4515 need to sort the entries ascending. */
4516 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
4518 asection *sec = bfd_get_section_by_name (abfd, ".pdata");
4520 if (sec)
4522 bfd_size_type x = sec->rawsize;
4523 bfd_byte *tmp_data = NULL;
4525 if (x)
4526 tmp_data = bfd_malloc (x);
4528 if (tmp_data != NULL)
4530 if (bfd_get_section_contents (abfd, sec, tmp_data, 0, x))
4532 qsort (tmp_data,
4533 (size_t) (x / 12),
4534 12, sort_x64_pdata);
4535 bfd_set_section_contents (pfinfo->output_bfd, sec,
4536 tmp_data, 0, x);
4538 free (tmp_data);
4540 else
4541 result = false;
4544 #endif
4546 rsrc_process_section (abfd, pfinfo);
4548 /* If we couldn't find idata$2, we either have an excessively
4549 trivial program or are in DEEP trouble; we have to assume trivial
4550 program.... */
4551 return result;