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